我有一个从 Web 请求返回的类别列表,采用 JSON 格式。一个例子可能是:
"categories":[["Descriptive Cat 1 Name","cat1label"]]
如何在对象中表示?我目前有一个名为 Category 的对象,并且使用它的方式如下:
private List<Category> categories;
Category 对象看起来像:
class Category {
private String descrName;
private String label;
.. getters and setters..
}
当尝试使用 GSON 进行解码时,我收到此错误:
01-27 21:44:46.149:错误/AndroidRuntime(843):com.google.gson.JsonParseException:需要数组但找到对象:Category@437d1ff8
有什么建议吗?我也可以让它们作为地图返回,尽管 JSON 结果中的 K,V 不是 V,K,可以这样映射吗?
如果我完全放弃 Category 对象,并将其映射为:
private List<List<String,String>> categories;
但是有更好的方法来表示该数据吗?
缺口
I have a list of categories coming back from a web request, in JSON format. An example might be:
"categories":[["Descriptive Cat 1 Name","cat1label"]]
How would that be represented in the object? I currently have an object called Category, and am using it like:
private List<Category> categories;
The Category object looks something like:
class Category {
private String descrName;
private String label;
.. getters and setters..
}
When attempting to decode with GSON I get this eror:
01-27 21:44:46.149: ERROR/AndroidRuntime(843): com.google.gson.JsonParseException: Expecting array but found object: Category@437d1ff8
Any suggestions? I would also be OK having those come back as a map, although instead of K,V in the JSON results they would be V,K, could it be mapped that way?
It does work if I ditch the Category object all together, and just map it as:
private List<List<String,String>> categories;
But is there a better way to represent that data?
Nick
发布评论
评论(4)
正如 @Dante617 正确指出的那样,您的 JSON 表示不正确。正确的表示是
现在,这可以被认为是“类别”标题和类别对象列表的映射。 则映射它的 Java 对象将是
Map>
。因此,如果您像上面那样以某种方式正确地重新格式化字符串, 这是您将如何解析。
如果你的 Java 对象看起来像这样
输出将显示如下
As @Dante617 correctly pointed, your JSON representation is not correct. The correct representation is
Now, this can be thought of as a map of "categories" title and list of Category objects. So, the Java object, that maps it, will be
Map<String, List<Category>>
If you somehow reformat your string correctly like the one above. Here is how you would parse.
If your Java object looks like this
The output will show like this
我不熟悉 GSON,但我不确定应用程序如何将字符串映射到对象中的字段。看起来您想要一个更像这样的 JSON 结构:
这可能有助于动态创建 Java 对象。
I'm not familiar with GSON, but I'm not sure how the application could map the strings to the fields in your object. It seems like you want a JSON structure more like:
That might help in being able to dynamically create the Java objects.
与其他人的想法相反,这不是无效的 JSON。
[[]]
只是一个二维数组。用 Java 术语来说,它映射如下:或者
In contrary to what others think, that's not invalid JSON. The
[[]]
is just a two-dimensional array. In Java terms, it maps as follows:or
感谢大家的意见。不幸的是,这是我正在使用的公共网络服务(Yelp v2 API),我无法更改它们返回的数据的格式。这就是我现在坚持的,效果很好:
Thanks for the input folks. Unfortunately this is a public web service I'm utilizing (the Yelp v2 API) and I can't change the format of the data they are returning. This is what I stuck with for now which is working fine: