我知道有很多关于 GSON 的 JSON 问题,但没有一个与我直接相关。我的 JSON 格式不同。
我有一个 JSON 数据,我想使用 GSON 解析它,如下所示:
[
{
"foo":"1",
"bar":[ { "_id":"bar1"} ],
"too":["mall", "park"]
}
]
我有模型类:
ItemArray 类
public class ItemArray
{
List<Item> itemArray;
//Get set here
}
元素等级
public class Item
{
String foo;
List<Bar> bar;
List<String> too;
//Get set here
}
酒吧类
public class Bar
{
String id;
//Get set here
}
问题来了。 JSON 格式是否正确?如果是,模型类的格式是否正确?
如果没有,请将我推向正确的方向。提前致谢!
附言。如果需要,我可以修改 JSON 数据格式。
最佳答案
根据您的 json,您应该只需要:
public class ItemArray extends List<Item> {
}
如果你想保留你的 java 类并更改你的 json,它应该是:
{
itemArray: [
{
"foo":"1",
"bar":[ { "_id":"bar1"} ],
"too":["mall", "park"]
}
]
}
哦,Bar 的 id 和 _id 不匹配:
public class Bar
{
String _id;
//Get set here
}
您还可以在 Json 反序列化过程中使用注释来更改字段的名称。
最后但同样重要的是,考虑更好地输入您的值(value)观。如果不是,请不要将任何数据视为字符串,您不会在 Java 代码中进行大量处理来转换内容。例如:
"foo" : 1,
并将 foo 视为 int 数据成员,而不是 String。
关于java - 使用Gson解析Json数组和没有名字的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13736122/