2

I have a class POJO

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

I have a 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 it is not possible, is it possible to get Pojo object which holds just first element of json string i.e. in this case id="1a" and name="foo"?

2
  • Seems similar to this post about array deserialization. Commented Sep 30, 2013 at 14:44
  • Can I ask you why you removed the accepted answer? Commented Sep 30, 2013 at 15:34

3 Answers 3

5

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 
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

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

2 Comments

You should also explain your answer, not just post a code.
Thanks guys, for the suggestion. I will update my answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.