我有一个 JSON 文件,数组内有多个条目。这些条目中的每一个都需要映射到一个 java 对象。这是我正在测试的 JSON 字符串( http://jsonlint.com/ 验证了下面的 JSON,但我必须删除在实际 Java 测试中使用的所有转义字符),
[{
"LocId":99,
"typeId":99,
"name":"foo",
"parentId":99,
"geoCode":
{
"type":"foo",
"coordinates":
[{
"latitude":99.0,
"longitude":99.0
}]
}
,
"LocId":8,
"typeId":99,
"name":"foo",
"parentId":99,
"geoCode":
{
"type":"foo",
"coordinates":
[{
"latitude":99.0,
"longitude":99.0
}]
}
}]
我像这样读取这个字符串,
String str = "The JSON string shown above";
InputStream is = new ByteArrayInputStream(str.getBytes());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
LocIdClass[] locations = new Gson().fromJson(br, LocIdClass[].class);
但是我的位置数组的大小始终为 1,并且仅存储 JSON 字符串中的最后一个条目。
for(int i=0; i<locations.length; i++)
System.out.println(locations[i]);
System.out.println("The size of the array is " + locations.length);
我不确定为什么只会检索 JSON 字符串中的最后一个条目,而会跳过其他条目。我引用了这篇SO文章来找出POJO数组Jackson - Json to POJO With Multiple Entries .
最佳答案
您当前的 json 负载有错误,请尝试以下操作:
[
{
"LocId": 99,
"typeId": 99,
"name": "foo",
"parentId": 99,
"geoCode": {
"type": "foo",
"coordinates": [
{
"latitude": 99,
"longitude": 99
}
]
}
},
{
"LocId": 8,
"typeId": 99,
"name": "foo",
"parentId": 99,
"geoCode": {
"type": "foo",
"coordinates": [
{
"latitude": 99,
"longitude": 99
}
]
}
}
]
编辑:为了避免将来出现此问题,您可以使用 jsonlint.com 检查您的 json。确保它是您所期望的。
关于java - POJO 条目的 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30740225/