Array of JSON Object to Java Pojo

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:
Sample Image

How to use it:

  1. Select target language. Java in your case.
  2. Select source. JSON in your case.
  3. 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).
  4. Select other optional configuration options like Include getters and setters. You can do that in your IDE as well.
  5. Select 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.

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



Leave a reply



Submit