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
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>>(){});
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));
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With