我将使用MOXy来解析以下结构的JSON:
现在,调试以下代码:
[
{
"page": 1,
"pages": 1
},
[
{
"indicator": {
"id": "IC.BUS.EASE.XQ",
"value": "Ease of doing business index"
},
"country": {
"id": "1A",
"value": "Arab World"
},
"value": "113.952380952381",
"date": "2014"
},
...
]
]
数组的第一个元素是一个对象,第二个元素是另一个由复杂元素组成的数组。我在这里真的很努力地搜索了SO和MOXy文档,但没有找到类似的例子。
我的最佳尝试是将json文档映射到JAVA类,如下所示。根类是CountryDataResponse(省略getter和setter):
@XmlRootElement
@XmlType(propOrder ={"paginationInfo", "dataArray"})
public class CountryDataResponse {
private DataArray dataArray;
private PaginationInfo paginationInfo;
}
我能看到这个会失败,因为它不是一个数组,但我完全迷失了方向。
PaginationInfo类模拟了根数组的第一个元素,DataArray类包装了第二个元素,即Data类元素的数组。此外,我还为每个Data元素内部的复杂类型创建了Indicator和Country类。
主要的类(省略了Indicator和Country):
@XmlRootElement(name = "paginationInfo")
@XmlAccessorType(XmlAccessType.FIELD)
public class PaginationInfo {
private int page;
private int pages;
}
@XmlRootElement( name = "dataArray" )
public class DataArray {
List<Data> datas;
}
@XmlRootElement(name="data")
@XmlAccessorType(XmlAccessType.FIELD)
public class Data {
private Indicator indicator;
private Country country;
private String date;
private double value;
}
现在,调试以下代码:
public static void main(String args[]) {
String test = "[{\"page\": 1,\"pages\": 1,\"per_page\": \"1000\",\"total\": 248},"
+ "["
+ "{\"indicator\": {\"id\": \"NY.GDP.MKTP.CD\",\"value\": \"GDP (current US$)\"},"
+ "\"country\": {\"id\": \"1A\",\"value\": \"Arab World\"},"
+ "\"value\": \"2853079422103.94\","
+ "\"decimal\": \"1\","
+ "\"date\": \"2013\"},"
+ "{\"indicator\": {\"id\": \"NY.GDP.MKTP.CD\",\"value\": \"GDP (current US$)\"},"
+ "\"country\": {\"id\": \"S3\",\"value\": \"Caribbean small states\"},"
+ "\"value\": \"67033118185.1864\","
+ "\"decimal\": \"1\","
+ "\"date\": \"2013\"}"
+ "]]";
JAXBContext jc = JAXBContext.newInstance(CountryDataResponse.class, Country.class, Data.class, DataArray.class, Indicator.class, PaginationInfo.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON);
unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false);
Object res = unmarshaller.unmarshal(json, CountryDataResponse.class);
}
res对象(JAXBElement类)具有ArrayList类型的值。数组的第一个元素是CountryDataResponse类的对象(应该是PaginationInfo),第二个元素是另一个ArrayList,其中的元素也是CountryDataResponse类的实例(它们应该是Data实例)。请问是否有人能帮我解决这个问题?或者这只是一个格式不正确的JSON,无法自动反序列化正确?谢谢您提前的帮助。