[英]How to parse a nested JSON response to a list of Java objects
我希望將帶有嵌套JSON數據的響應解析為Java對象列表。 JSON響應采用以下格式。
{
"IsSuccess": true,
"TotalCount": 250,
"Response": [
{
"Name": "Afghanistan",
"CurrencyCode": "AFN",
"CurrencyName": "Afghan afghani"
},
{
"Name": "Afghanistan",
"CurrencyCode": "AFN",
"CurrencyName": "Afghan afghani"
},
{
"Name": "Afghanistan",
"CurrencyCode": "AFN",
"CurrencyName": "Afghan afghani"
}
]
}
我有相應的Country類,可以將其解析為POJO。 我正在使用Jackson解析數據。
Client c = ClientBuilder.newClient();
WebTarget t = c.target("http://countryapi.gear.host/v1/Country/getCountries");
Response r = t.request().get();
String s = r.readEntity(String.class);
System.out.println(s);
ObjectMapper mapper = new ObjectMapper();
try {
List<Country> myObjects = mapper.readValue(s, new TypeReference<List<Country>>(){});
System.out.println(myObjects.size());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
實際的國家/地區列表與JSON字符串中的“響應”一起顯示。 我將如何檢索“響應”下的內容,然后將其解析為國家列表?
不確定所使用的客戶端API不能簡單地提供所需類型的實體。 大多數客戶端應具有實用程序方法來進行這種轉換。 無論如何,這是一種實現所需目標的方法:
final JsonNode jsonNode = mapper.readTree(jsonString);
final ArrayNode responseArray = (ArrayNode) jsonNode.get("Response");
//UPDATED to use convertValue()
final List<Country> countries = mapper.convertValue(responseArray, new TypeReference<List<Country>>(){});
Country.class
class Country {
@JsonProperty("Name")
public String name;
@JsonProperty("CurrencyCode")
public String currencyCode;
@JsonProperty("CurrencyName")
public String currencyName;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.