deserialize inner JSON object

后端 未结 3 756
星月不相逢
星月不相逢 2020-12-19 23:39

I have a class POJO

Class Pojo {
String id;
String name;
//getter and setter
}

I have a json like

{
    \"response\" : [
          


        
相关标签:
3条回答
  • 2020-12-20 00:12

    You can use the generic readTree with JsonNode:

    ObjectMapper mapper = new ObjectMapper();
    JsonNode root = mapper.readTree(json);
    JsonNode response = root.get("response");
    List<Pojo> list = mapper.readValue(response, new TypeReference<List<Pojo>>() {});
    
    0 讨论(0)
  • 2020-12-20 00:20

    You'll first need to get the array

    String jsonStr = "{\"response\" : [ { \"id\" : \"1a\",  \"name\" : \"foo\"},{ \"id\" : \"1b\",\"name\" : \"bar\"  } ]}";
    ObjectMapper mapper = new ObjectMapper();
    JsonNode node = mapper.readTree(jsonStr);
    ArrayNode arrayNode = (ArrayNode) node.get("response");
    System.out.println(arrayNode);
    List<Pojo> pojos = mapper.readValue(arrayNode.toString(), new TypeReference<List<Pojo>>() {});
    
    System.out.println(pojos);
    

    prints (with a toString())

    [{"id":"1a","name":"foo"},{"id":"1b","name":"bar"}] // the json array 
    [id = 1a, name = foo, id = 1b, name = bar] // the list contents
    
    0 讨论(0)
  • 2020-12-20 00:29
    Pojo pojo;
    json = {
        "response" : [
            {
                "id" : "1a",
                "name" : "foo"
            }, 
            {
                "id" : "1b",
                "name" : "bar"
            }
        ]
    }
    ObjectMapper mapper = new ObjectMapper();
    JsonNode root = objectMapper.readTree(json);
    pojo = objectMapper.readValue(root.path("response").toString(),new TypeReference<List<Pojo>>() {});
    

    First, you have to create a JSON node with your JSON file. Now you have a JSON node. You can go to the desired location using path function of JSON node like what I did

    root.path("response")
    

    However this will return a JSON tree. To make a String, I have used the toString method. Now, you have a String like below " [ { "id" : "1a", "name" : "foo" }, { "id" : "1b", "name" : "bar" } ] " You can map this String with JSON array as following

    String desiredString = root.path("response").toString();
    pojos = objectMapper.readValue(desiredString ,new TypeReference<List<Pojo>>() {});
    
    0 讨论(0)
提交回复
热议问题