Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert JSON string into List of Java object?

This is my JSON Array :-

[ 
    {
        "firstName" : "abc",
        "lastName" : "xyz"
    }, 
    {
        "firstName" : "pqr",
        "lastName" : "str"
    } 
]

I have this in my String object. Now I want to convert it into Java object and store it in List of java object. e.g. In Student object. I am using below code to convert it into List of Java object : -

ObjectMapper mapper = new ObjectMapper();
StudentList studentList = mapper.readValue(jsonString, StudentList.class);

My List class is:-

public class StudentList {

    private List<Student> participantList = new ArrayList<Student>();

    //getters and setters
}

My Student object is: -

class Student {

    String firstName;
    String lastName;

    //getters and setters
}

Am I missing something here? I am getting below exception: -

Exception : com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.aa.Student out of START_ARRAY token
like image 330
Nitesh Avatar asked Jun 16 '17 12:06

Nitesh


3 Answers

You are asking Jackson to parse a StudentList. Tell it to parse a List (of students) instead. Since List is generic you will typically use a TypeReference

List<Student> participantJsonList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});
like image 57
Manos Nikolaidis Avatar answered Oct 07 '22 22:10

Manos Nikolaidis


For any one who looks for answer yet:

1.Add jackson-databind library to your build tools like Gradle or Maven

2.in your Code:

ObjectMapper mapper = new ObjectMapper();

List<Student> studentList = new ArrayList<>();

studentList = Arrays.asList(mapper.readValue(jsonStringArray, Student[].class));
like image 8
Sobhan Avatar answered Oct 07 '22 22:10

Sobhan


You can also use Gson for this scenario.

Gson gson = new Gson();
NameList nameList = gson.fromJson(data, NameList.class);

List<Name> list = nameList.getList();

Your NameList class could look like:

class NameList{
 List<Name> list;
 //getter and setter
}
like image 5
Pankaj Jaiswal Avatar answered Oct 08 '22 00:10

Pankaj Jaiswal