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.
JsonArray field in a JsonObject to Java Object
Use List<UserCart>
for array data in json and use @JsonProperty
for mapping different json node name to java object field. No need to use extra field (JsonArray Orders
) anymore.
@JsonProperty("Orders")
private List<UserCart> userCart;
Convert JSON array to Java Class Object List
Try this:
try {
JSONObject jsonObject = null;
yourJSONString.replace("\\", "");
jsonObject = new JSONObject(yourJSONString);
String newJSONString = jsonObject.get("GetCardsResult").toString();
JSONArray jsonMainArr = new JSONArray(newJSONString);
//now just loop the json Array
for (int i = 0; i < jsonMainArr.length(); ++i) {
JSONObject rec = jsonMainArr.getJSONObject(i);
card.set_id(rec.get("ID").toString());
//....
}
} catch (JSONException e) {
e.printStackTrace();
}
Creating a POJO model from a JSON with an array
You need to add some objects in your list!
e.g.
Notification test = new Notification();
test.getObject().add(new object()); //Add a new object in your object list
Creating POJO objects from JSON array String
ArrayList<LinkedTreeMap> list = gson.fromJson(json, ArrayList.class);
List<User> users= list.stream()
.map(s -> gson.fromJson(gson.toJson(s), User.class))
.collect(Collectors.toList());
POJO Creation from JSON Array (BufferReader)
Add your default constructor, empty constructor, by adding @NoArgConstructor
top of your POJO class.
Then simply convert your buffer reader JSON string to a list of POJO like this:
List<MyPOJO> eventList = mapper.readValue(myBufferedReader, new TypeReference<List<MyPOJO>>(){});
Mapping Json Array to POJO using Jackson
You can use ARRAY
shape for this object. You can do that using JsonFormat
annotation:
@JsonFormat(shape = Shape.ARRAY)
class ABC {
And deserialise it:
ABC[] abcs = mapper.readValue(json, ABC[].class);
EDIT after changes in question.
You example code could look like this:
JsonNode jsonNode = mapper.readTree(json);
if (jsonNode.isArray()) {
for (JsonNode node : jsonNode) {
String nodeContent = mapper.writeValueAsString(node);
ABC abc = mapper.readValue(nodeContent, ABC.class);
System.out.println("Data: " + abc.getA());
}
}
We can use convertValue
method and skip serializing process:
JsonNode jsonNode = mapper.readTree(json);
if (jsonNode.isArray()) {
for (JsonNode node : jsonNode) {
ABC abc = mapper.convertValue(node, ABC.class);
System.out.println("Data: " + abc.getA());
}
}
Or even:
JsonNode jsonNode = mapper.readTree(json);
ABC[] abc = mapper.convertValue(jsonNode, ABC[].class);
System.out.println(Arrays.toString(abc));
How to map/deserialize a JSON array to a POJO or POJO List?
You can use gson
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.1</version>
</dependency>
JsonParser jsonParser = new JsonParser();
JsonObject jo = (JsonObject)jsonParser.parse(str);
JsonArray jsonArr = jo.getAsJsonArray("netStatLinks");
List<NetStatLink> users = new ArrayList<NetStatLink>();
Gson gson = new Gson();
Type listType = new TypeToken<List<NetStatLink>>(){}.getType();
netStatLink = gson.fromJson(jsonArr ,listType);
Related Topics
How to Turn Off the Eclipse Code Formatter for Certain Sections of Java Code
How to Use Java Property Files
Find Java Classes Implementing an Interface
How to Connect to Oracle Using Service Name Instead of Sid
Spring Boot and Multiple External Configuration Files
The JPA Hashcode()/Equals() Dilemma
Setting Background Images in Jframe
Using Switch Statement with a Range of Value in Each Case
Difference Between Processbuilder and Runtime.Exec()
Which Is the Best Library for Xml Parsing in Java
Java Io Implementation of Unix/Linux "Tail -F"
Connecting to Remote Url Which Requires Authentication Using Java
Why Use a Prime Number in Hashcode
Round Up to 2 Decimal Places in Java
Should a Retrieval Method Return 'Null' or Throw an Exception When It Can't Produce the Return Value
How to Derive Module Descriptor for Auto Generated Module Names in Java 9