如何从json中获取json

时间:2016-11-10 07:30:33

标签: java json jackson

我有以下的json数据。

{
  "RestResponse" : {
    "messages" : [ "More webservices are available at http://www.groupkt.com/post/f2129b88/services.htm", "Total [249] records found." ],
    "result" : [ {
      "name" : "Afghanistan",
      "alpha2_code" : "AF",
      "alpha3_code" : "AFG"
    }, {
      "name" : "Åland Islands",
      "alpha2_code" : "AX",
      "alpha3_code" : "ALA"
    }, {
      "name" : "Albania",
      "alpha2_code" : "AL",
      "alpha3_code" : "ALB"
    }, {
      "name" : "Algeria",
      "alpha2_code" : "DZ",
      "alpha3_code" : "DZA"
    }]
  }
}

在这里,我需要遍历国家/地区名称并将其打印在我的控制台中。

我正在尝试以下代码。

ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> map = mapper.readValue(text, new TypeReference<Map<String, Object>>() {
            });

            Map<String, Object> map1 = (Map<String, Object>) map.get("RestResponse");
            Map<String, Object> map2 = (Map<String, Object>) map1.get("result");



            System.out.println(map1);

当我运行时,我得到例外

Exception in thread "main" java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.util.Map
    at onlyJava.Countries.getTheCurrentWeather(Countries.java:45)
    at onlyJava.Test.main(Test.java:6)

当我发表评论Map<String, Object> map2 = (Map<String, Object>) map1.get("result");时,它会给我从messages:....开始直到结束的结果。

请让我知道我哪里出错了,我该如何解决这个问题。

更新了代码。

ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> map = mapper.readValue(text, new TypeReference<Map<String, Object>>() {
            });

            Map<String, Object> map1 = (Map<String, Object>) map.get("RestResponse");
            List<Object> resultList = new ArrayList<Object>();
            resultList = mapper.readValue(map1.get("result"), new TypeReference<List<Object>>() {
            });

            System.out.println(resultList);

由于

3 个答案:

答案 0 :(得分:1)

你正在获得jsonObject。键“RestResponse”的值在{}括号内,它再次是一个json对象,这就是为什么你能够将它映射到Map。但是对于键“result”的值是在[]括号内,这是一个列表而不是json对象,所以你不能将它分配给Map。您应该创建一个Arraylist并将其分配给它。

答案 1 :(得分:1)

结果是类型列表,因此为了正确解析它,您需要执行以下操作:

List<Object> resultList = new ArrayList<Object>();
resultList = JsonMapper.readValue(map1.get("result"), new TypeReference<List<Object>>(){});

此外,为了简化而不是逐个解析节点,您可以创建结果对象的POJO并让json映射器进行自动转换。

编辑:为了获得正确的映射,请创建root和后续对象的pojo并按以下方式解析它:

ObjectMapper mapper = new ObjectMapper();
    mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
    String jsonString = "{\"RestResponse\":{\"messages\":[\"More webservices are available at http://www.groupkt.com/post/f2129b88/services.htm\", \"Total [249] records found.\" ],\"result\":[{\"name\":\"Afghanistan\",\"alpha2_code\":\"AF\",\"alpha3_code\":\"AFG\"}, {\"name\":\"Åland Islands\",\"alpha2_code\":\"AX\",\"alpha3_code\":\"ALA\"}, {\"name\":\"Albania\",\"alpha2_code\":\"AL\",\"alpha3_code\":\"ALB\"}, {\"name\":\"Algeria\",\"alpha2_code\":\"DZ\",\"alpha3_code\":\"DZA\"}]}}";
    Root response = null;
    try {

        response = mapper.readValue(jsonString, Root.class);

        for (Result result : response.getRestResponse().getResult())
            System.out.println("Country Name: " + result.getName());
    } catch (IOException e) {
        e.printStackTrace();
    }

Root Class:

RestResponseNode RestResponse;

public RestResponseNode getRestResponse() {
    return RestResponse;
}

public void setRestResponse(RestResponseNode restResponse) {
    RestResponse = restResponse;
}

@Override
public String toString() {
    return "Root [RestResponseNode=" + RestResponse + "]";
}

RestResponseNode类:

List<String> messages;
List<Result> result;

public List<String> getMessages() {
    return messages;
}

public void setMessages(List<String> messages) {
    this.messages = messages;
}

public List<Result> getResult() {
    return result;
}

public void setResult(List<Result> result) {
    this.result = result;
}

@Override
public String toString() {
    return "RestResponseNode [messages=" + messages + ", result=" + result + "]";
}

结果类:

String name;
String alpha2_code;
String alpha3_code;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getAlpha2_code() {
    return alpha2_code;
}

public void setAlpha2_code(String alpha2_code) {
    this.alpha2_code = alpha2_code;
}

public String getAlpha3_code() {
    return alpha3_code;
}

public void setAlpha3_code(String alpha3_code) {
    this.alpha3_code = alpha3_code;
}

@Override
public String toString() {
    return "Result [name=" + name + ", alpha2_code=" + alpha2_code + ", alpha3_code=" + alpha3_code + "]";
}

答案 2 :(得分:1)

你正在获得jsonObject。密钥&#34; RestResponse&#34;的价值内部&#34;结果&#34;是jsonArray下面的代码,用于从json中查找国家名称。

使用Json Library进行测试:org.json

String jsonString = "{ \"RestResponse\" : { \"messages\" : [ \"More webservices are available at http://www.groupkt.com/post/f2129b88/services.htm\", \"Total [249] records found.\" ], \"result\" : [ { \"name\" : \"Afghanistan\", \"alpha2_code\" : \"AF\", \"alpha3_code\" : \"AFG\" }, { \"name\" : \"Åland Islands\", \"alpha2_code\" : \"AX\", \"alpha3_code\" : \"ALA\" }, { \"name\" : \"Albania\", \"alpha2_code\" : \"AL\", \"alpha3_code\" : \"ALB\" }, { \"name\" : \"Algeria\", \"alpha2_code\" : \"DZ\", \"alpha3_code\" : \"DZA\" }] } }";
JSONObject jObject = new JSONObject(jsonString);
JSONObject obj1 = jObject.getJSONObject("RestResponse");
JSONArray result = obj1.getJSONArray("result");
for (int i = 0; i < result.length(); i++) {
    JSONObject company = result.getJSONObject(i);
    String name = company.getString("name");
    System.out.println("Country Name : "+name);
}

输出:

Country Name : Afghanistan
Country Name : Åland Islands
Country Name : Albania
Country Name : Algeria