我将json数组解析为指定对象的java集合时遇到问题。
JSON回复:
{
"data": [
{
"country_code": "US",
"name": "United States",
"supports_region": "true",
"supports_city": "true"
},
{
"country_code": "CA",
"name": "Canada",
"supports_region": "true",
"supports_city": "true"
},
{
"country_code": "GB",
"name": "United Kingdom",
"supports_region": "true",
"supports_city": "true"
}
]
}
接下来我有一个单一国家的班级:
@JsonIgnoreProperties(ignoreUnknown = true)
public class TargetCountry {
@JsonProperty("country_code")
private String countryCode;
@JsonProperty("name")
private String name;
public String getCountryCode() {
return countryCode;
}
public String getName() {
return name;
}
}
我正在使用Jackson库将json解析为java。
如果没有包含数组的额外字段“数据”,一切都会好的。
由于“数据”字段,我不想再制作包装类。如何以优雅的方式解析该响应以接收:Collection<TargetCountry>
,例如:
RestTemplate restTemplate = new RestTemplate();
TargetCountry[] countryList = restTemplate.getForObject(uri, TargetCountry[].class);
答案 0 :(得分:0)
您可以考虑两个选项:
withRootName()
方法。您可能需要咨询this question如何自定义映射器。以下是示例:
public class JacksonRootValue {
public static final String JSON = "{\n" +
" \"data\": [\n" +
" {\n" +
" \"country_code\": \"US\", \n" +
" \"name\": \"United States\", \n" +
" \"supports_region\": \"true\", \n" +
" \"supports_city\": \"true\"\n" +
" }, \n" +
" {\n" +
" \"country_code\": \"CA\", \n" +
" \"name\": \"Canada\", \n" +
" \"supports_region\": \"true\", \n" +
" \"supports_city\": \"true\"\n" +
" }, \n" +
" {\n" +
" \"country_code\": \"GB\", \n" +
" \"name\": \"United Kingdom\", \n" +
" \"supports_region\": \"true\", \n" +
" \"supports_city\": \"true\"\n" +
" }\n" +
" ]\n" +
"}";
@JsonIgnoreProperties(ignoreUnknown = true)
public static class TargetCountry {
@JsonProperty("country_code")
public String countryCode;
public String name;
@Override
public String toString() {
return "TargetCountry{" +
"countryCode='" + countryCode + '\'' +
", name='" + name + '\'' +
'}';
}
}
public static void main(String[] args) throws IOException {
ObjectMapper mapper1 = new ObjectMapper();
// customize the mapper
mapper1.setConfig(mapper1.getDeserializationConfig().withRootName("data"));
TargetCountry[] result1 = mapper1.readValue(JSON, TargetCountry[].class);
System.out.println("Option 1: " + Arrays.toString(result1));
// read as a JsonNode and then convert to an object
ObjectMapper mapper2 = new ObjectMapper();
JsonNode node = mapper2.readValue(JSON, JsonNode.class);
TargetCountry[] result2 = mapper2.treeToValue(node.path("data"), TargetCountry[].class);
System.out.println("Option 2: " + Arrays.toString(result2));
}
}
输出:
Option 1: [TargetCountry{countryCode='US', name='United States'}, TargetCountry{countryCode='CA', name='Canada'}, TargetCountry{countryCode='GB', name='United Kingdom'}]
Option 2: [TargetCountry{countryCode='US', name='United States'}, TargetCountry{countryCode='CA', name='Canada'}, TargetCountry{countryCode='GB', name='United Kingdom'}]