0

I see issues in parsing below json to java object using jackson api.

Json String
[
  [
    {
      "id": "6555",
      "fname": "hello",
      "lname": "test"
    },
    {
      "id": "6588",
      "fname": "world",
      "lname": "test"
    }
  ]
]

I have created below pojos (removed setters and getters).

public class Result {
   List<Student> studentList;
}

public class Student{
   private String id;
   private String fname;
   private String lname;
}

ObjectMapper mapper = new ObjectMapper();
List<Result > responseList = mapper.readValue(jsonStr, new TypeReference<List<Result>>(){});

Jackson has throwing exception

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of out of START_ARRAY token at [Source:

Do I need to any specific jackson annotation to Result object?

1
  • 1
    I would recommend going the other way around, create a list of results and try writing it using your mapper :) Commented Dec 13, 2018 at 19:28

2 Answers 2

1

You don't need to Result class, it is redundant. You need to parse it as List<List<Student>> because your json structure starts as array and contains another arrays.

Here is how you can parse your :

ObjectMapper mapper = new ObjectMapper();
try {
    List<Result> responseList = mapper.readValue(
            Files.readAllBytes(Paths.get("test.json")),
            new TypeReference<List<List<Student>>>() {});

} catch (IOException e) {
    e.printStackTrace();
}

Output :

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

thank you.. Yup. I can go with List<List<Student>> and its worked.
1

If I were trying to write JSON to match the structure you've defined, I'd want:

[ 
    { 
        "studentList": 
        [
            {
                "id": "6555",
                "fname": "hello",
                "lname": "test"
            },
            {
                "id": "6588",
                "fname": "world",
                "lname": "test"
            }
        ]
    }
]

Based on the JSON you've laid out, I'd expect Jackson to see that as a List<List<Student>>.

1 Comment

Thank you Geoffrey. I dont have control and its rest api response.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.