Array of JSON Object to Java POJO
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:
- Select target language.
Java
in your case. - Select source.
JSON
in your case. - Select annotation style. This can be tricky because it depends from library you want to use to serialise/deserialise
JSON
. In case schema is simple do not use annotations (None
option). - Select other optional configuration options like
Include getters and setters
. You can do that in yourIDE
as well. - Select
Preview
button. In case schema is big downloadZIP
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.
In the above json you have ownerName
as property, pets
as List of objects
public class Response {
private String ownerName;
private List<Pet> pets;
// getters and setters
}
Pet POJO
public class Pet {
private String name;
//getters and setters
}