如何将嵌套的JSON响应解析为Java对象列表

时间:2018-04-01 15:20:52

标签: java json jackson gson pojo

我希望将带有嵌套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。我使用杰克逊解析数据。

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();
        }

实际的国家/地区列表正在响应&#34;响应&#34;在JSON字符串中。如何检索“响应”下的内容,然后将其解析为国家/地区列表?

1 个答案:

答案 0 :(得分:2)

不确定您使用的客户端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;
 }