Arun
Arun

Reputation: 609

Keeping POJO intact how to inject new field in JSON using Jackson?

My ultimate aim is, I have list of POJO. I need to convert as a JSON String using Jackson. While converting as JSON. I need to add few more keys. In order to do that, I have only solution. If I convert as list of POJO into list of ObjectNode so that I can add info in ObjectNode. After that I will convert as JSON String.

List<dummyPOJO> dummyPOJO = getPOJO(); ObjectNode objectNode = mapper.convertValue(dummyPOJO, new TypeReference<ArrayList<ObjectNode>>(){});

This code is giving an follow error

java.lang.ClassCastException: java.util.ArrayList cannot be cast to com.fasterxml.jackson.databind.node.ObjectNode

Please let me know if any solution available. Thanks in Advance :)

Upvotes: 0

Views: 413

Answers (1)

Kousik Mandal
Kousik Mandal

Reputation: 720

The following code looks to be incorrect

ObjectNode objectNode = mapper.convertValue(dummyPOJO, new TypeReference<List<ObjectNode>>(){});

It should fail with

Type mismatch: cannot convert from List<ObjectNode> to ObjectNode

It could be updated to

List<ObjectNode> objectNodes = mapper.convertValue(dummyPOJO, new TypeReference<List<ObjectNode>>(){});

Without updating POJO, to add an extra field in json you can use following procedure

This is a simple POJO having 3 fields firstName, lastName and age

Person.java

package sep2020;

public class Person {
    public String firstName;
    public String lastName;
    public int age;

    public Person() {
    }

    public Person(String firstName, String lastName, int age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    public String toString() {
        return "[" + firstName + " " + lastName + " " + age + "]";
    }
}

Now will create some Person objects and will convert them List<ObjectNode> structure.

Then will iterate over all ObjectNode and will add new filed Sex in the Person ObjectNode.

But POJO structure will remain unchanged.

JSONListConverter.java

package sep2020;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class JSONListConverter {
    public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

        // Define map which will be converted to JSON
        List<Person> personList = Stream.of(new Person("A", "B", 34),
                new Person("C", "D", 75), new Person("E", "F", 21),
                new Person("G", "H", 55)).collect(Collectors.toList());

        List<ObjectNode> objectNodes = objectMapper.convertValue(personList,
                new TypeReference<List<ObjectNode>>() {
                });

        JsonNode jsonNode = objectMapper.convertValue(objectNodes,
                JsonNode.class);
        // Existing Json structure
        System.out.println("Existing Json:\n"
                + objectMapper.writeValueAsString(jsonNode));
        System.out.println("\n\n");
        // Adding an extra field
        if (objectNodes != null && objectNodes.size() > 0) {
            for (ObjectNode objectNode : objectNodes) {
                objectNode.put("Sex", "M");
            }
        }
        jsonNode = objectMapper.convertValue(objectNodes, JsonNode.class);
        // Updated Json structure
        System.out.println("Updated Json:\n"
                + objectMapper.writeValueAsString(jsonNode));
    }
}

Output:

Existing Json:

[ {
  "firstName" : "A",
  "lastName" : "B",
  "age" : 34
}, {
  "firstName" : "C",
  "lastName" : "D",
  "age" : 75
}, {
  "firstName" : "E",
  "lastName" : "F",
  "age" : 21
}, {
  "firstName" : "G",
  "lastName" : "H",
  "age" : 55
} ]



Updated Json:

[ {
  "firstName" : "A",
  "lastName" : "B",
  "age" : 34,
  "Sex" : "M"
}, {
  "firstName" : "C",
  "lastName" : "D",
  "age" : 75,
  "Sex" : "M"
}, {
  "firstName" : "E",
  "lastName" : "F",
  "age" : 21,
  "Sex" : "M"
}, {
  "firstName" : "G",
  "lastName" : "H",
  "age" : 55,
  "Sex" : "M"
} ]

Upvotes: 1

Related Questions