如何反序列化 JSON 对象内的数组?
我不知道如何使用 Gson 反序列化 JSON 对象内的数组。我尝试反序列化的 json 对象如下所示:
{"item0":3,
"item1":1,
"item2":3,
"array":[
{"arrayItem1":321779321,
"arrayItem2":"asdfafd",
"arrayItem3":"asasdfadf"}]}
我设法构建一个如下所示的类:
public class Watchlist {
private int itemn0;
private int itemn1;
private int itemn2;
private Object array;
}
但是当 gson 尝试反序列化数组时,它会抛出异常:
com.google.gson.JsonParseException: Type information is unavailable, and the target object is not a primitive: <my gson array>
有人能告诉我如何反序列化吗?
I can't work out how to deserialize an array inside a JSON object using Gson. The json object that i'm trying to deserialize looks like this:
{"item0":3,
"item1":1,
"item2":3,
"array":[
{"arrayItem1":321779321,
"arrayItem2":"asdfafd",
"arrayItem3":"asasdfadf"}]}
I manage to build a class that looks like this:
public class Watchlist {
private int itemn0;
private int itemn1;
private int itemn2;
private Object array;
}
But when gson tries to deserialize the array it throws an exception:
com.google.gson.JsonParseException: Type information is unavailable, and the target object is not a primitive: <my gson array>
Can someone please tell me how to deserialize this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的“数组”是一个数组。
所以在watchList类中
现在使用下载Gson
参考:http://primalpop.wordpress。 com/2010/06/05/parsing-json-using-gson-in-android/
your "array" is an Array.
so in watchList class
Now use download Gson
refer: http://primalpop.wordpress.com/2010/06/05/parsing-json-using-gson-in-android/
这里有几个问题:
第一,我认为您没有像您想象的那样使用数组。您有“arrayItem1”到 3,但它们包含在数组内的单个 JSON 对象中...因此数组实际上只有一项。
数组可能应该是这样的:
第二个是 Java 类中的
array
类型是Object
... 这不会为 Gson 提供任何可供使用的类型信息用于翻译对象。通常,您需要将数组映射到的对象类型声明为List
或List
等。这为它提供了必要的类型信息...JSON 数组可以映射到List
,并且String
类型参数告诉它将数组的内容转换为什么类型。您的示例中的数组的问题是它不是同质的......它有一个数字和两个字符串。一般来说,应该避免在数组/集合中混合这样的类型。但是,您可以将
array
对象的类型声明为List
...您将获得以下形式的String
号码。There's a couple of problems here:
One, I don't think you're using the array like you think you are. You have "arrayItem1" through 3, but they are contained in a single JSON object within the array... so the array actually only has one item.
The array should probably be something like:
The second is that the type of
array
in your Java class isObject
... that doesn't give Gson any type information to use for translating the object. Normally, you'd want to declare the type of the object the array maps to asList<String>
orList<Integer>
or some such. This gives it the necessary type information... a JSON array can map to aList
, and theString
type parameter tells it what type to translate the array's contents to.The problem with the array in your example is that it isn't homogenous... it has a number and two strings in it. Generally, mixing types like this in an array/collection should be avoided. You can, however, declare the type of your
array
object asList<String>
... you'll just get theString
form of the number.