From time to time I get some of this odd API response from requesting information for a specific something. I expect the response data to be a simple JSON object. Instead I am looking at a JSON array. I suppose that is still simple enough and it’s not so odd. This kind of response happens all the time, right? It does makes the response formatting weird in that why does it have to be in an array when it’s expected that only a single element is returned in the response.
Say for example I have this API endpoint here to get a Person’s basic information by providing a unique ID:
http://localhost:8080/persons/12345
The response looks something like the following,
[
{
"id": 12345,
"firstName": "Jose",
"lastName": "Yamut",
"suffix": "Jr.",
"gender": "male"
}
]
How do I read this JSON data into my POJO?
// Getter and Setter methods omitted for brevity
private class Person {
private String firstName;
private String lastName;
private String suffix;
private String gender;
}
Here are some of the ways using Jackson’s popular ObjectMapper class, of course, so the passed value gets mapped directly to my object.
First is by using Jackson’s generic abstract class called TypeReference. This way I am able to put the value into a List directly. Below is a block of code that does the trick.
// Other code omitted for brevity
final ObjectMapper objectMapper = new ObjectMapper();
try {
List<Person> persons = objectMapper.readValue(jsonData, new TypeReference<List<Person>>(){});
System.out.println("Person info: " + persons.get(0).toString()); // <-- Just to show the output fast
} catch (IOException e) {
e.printStackTrace();
}
Note the variable persons although I’m only expecting one Person object because there was an ID provided as parameter in the GET request. I’m assuming the index is zero. But I can use the size() method of List if need be. For example purposes, I didn’t (obviously!).
The second approach would be through the trusty old array. I’ll pass the value to an array of Person. The code will now look slightly differently like this,
// Other code omitted for brevity
final ObjectMapper objectMapper = new ObjectMapper();
try {
Person[] persons = objectMapper.readValue(jsonData, Person[].class);
System.out.println("Person info: " + persons[0].toString()); // <-- Assuming index is zero, read note.
} catch (IOException e) {
e.printStackTrace();
}
Know of a third or some other way to do this? Still using Jackson ObjectMapper. I’ll try to see if there are more than 2 ways to skin a cat, as the old adage goes but slightly paraphrasing. You get the picture.
Similar Posts:
- > Divide A List To Sub-Lists Via Collectors September 4, 2021
- > Deserializing JSON Object With Unknown Properties October 15, 2020
- > Removing Null Values In A List Using Java 8 Stream October 22, 2020
- > Nested Java Bean Validation May 27, 2021
- > Read YAML in Spring Boot January 24, 2021