Deserialize the internal JSON object

I have a POJO class

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

I have json like

{
    "response" : [
        {
            "id" : "1a",
            "name" : "foo"
        }, 
        {
            "id" : "1b",
            "name" : "bar"
        }
    ]
}

I am using Jackson ObjectMapper for deserialization. How can I get List<Pojo>without creating any other parent class?

If this is not possible, is it possible to get an object Pojothat contains only the first element of the json string, i.e. in this case id="1a"and name="foo"?

+2
source share
3 answers

First you need to get an 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 (s toString())

[{"id":"1a","name":"foo"},{"id":"1b","name":"bar"}] // the json array 
[id = 1a, name = foo, id = 1b, name = bar] // the list contents
+3
source

You can use shared 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>>() {});
+2
source
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>>() {});

JSON JSON. JSON. , JSON,

root.path("response")

However, this will return a JSON tree. To make a string, I used the toString method. Now you have a line as shown below "[{" id ":" 1a "," name ":" fu "}, {" id ":" 1b "," name ":" bar "}]" You can map this string to a JSON array as follows

String desiredString = root.path("response").toString();
pojos = objectMapper.readValue(desiredString ,new TypeReference<List<Pojo>>() {});
0
source

Source: https://habr.com/ru/post/1688260/


All Articles