【发布时间】:2015-06-09 18:41:10
【问题描述】:
我有一个 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。
【问题讨论】:
-
您的数据正确吗?当第二个对象启动时,它似乎缺少
{。 -
在jsonlint.com 中成功验证为正确的 JSON。我可以通过查看它来判断它是 JSON 数组中的两个实体,并且语法对我来说是正确的。
-
查看jsonlint文本区格式化后的json:原来“json”的一整段被去掉了。
-
哦,哇,我没注意到。问题出在哪里。
-
你将如何正确地重写它,因为它看起来像是具有两个对象的数组所需的格式。