JSON POJO 条目数组
JSON Array Of Entries to POJO
我有一个 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 post 来计算 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。确保它符合您的预期。
我有一个 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 post 来计算 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。确保它符合您的预期。