Converting this JSON object as a class in java, how would the mapping be in your POJO Class?
{
"ownerName": "Robert",
"pets": [
{
"name": "Kitty"
},
{
"name": "Rex"
},
{
"name": "Jake"
}
]
}
Above JSON Array is a collection of JSON Objects or a List of Employees. We have created a Employee POJO class in previous post and we can reuse the same. That is how reusability is one of the major advantage of POJO classes. We do not need any other classes. We just need to create a List of Employees .
In this article, we'll convert a JSON array into a Java Array and Java List using Jackson. Since we're using Jackson, you'll have to add it to your project. If you're using Maven, it's as easy as adding the dependency: Since we're mapping from JSON to our own objects, let's go ahead and define a POJO:
; Using Jackson's ObjectMapper class, it's easy to read values and map them to an object, or an array of objects. We just use the readValue () method, passing the JSON contents and the class we'd like to map to. Since we're mapping to an array of Language, we'll also specify this in the readValue () method:
In this article, we've used Jackson to parse and map the values from a JSON String and file into a Java array and list. This is done via the readValue () method, by specifying the JSON contents (String or file) and by specifying the POJO we'd like to map to.
This kind of question is very popular and needs general answer. In case you need generate POJO
model based on JSON
or JSON Schema
use www.jsonschema2pojo.org. Example print screen shows how to use it:
How to use it:
Java
in your case.JSON
in your case.JSON
. In case schema is simple do not use annotations (None
option).Include getters and setters
. You can do that in your IDE
as well.Preview
button. In case schema is big download ZIP
with generated classes.For your JSON
this tool generates:
public class Person {
private String ownerName;
private List <Pet> pets = null;
public String getOwnerName() {
return ownerName;
}
public void setOwnerName(String ownerName) {
this.ownerName = ownerName;
}
public List < Pet > getPets() {
return pets;
}
public void setPets(List < Pet > pets) {
this.pets = pets;
}
}
public class Pet {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
For Android Studio
and Kotlin
read RIP http://www.jsonschema2pojo.org.
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