1

I have a Java object class, say, Student. How to convert it to an ObjectNode? It can be a nested object (multi-level nesting).

I am trying following code to convert the object to ObjectNode, but it is first converting the object to a String and then converting it to ObjectNode which looks costly operation.

ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

try {
    String json = mapper.writeValueAsString(student);
    JsonNode jsonNode = mapper.readTree(json);
    ObjectNode objectNode = jsonNode.deepCopy();
    return objectNode;
} catch (Exception e) {
    // Handle exception
}

I am looking for a better approach because I feel by this approach, I am doing 2 levels serialization/deserialization.

public class Student {
    public String name;
    public int id;
    public ArrayList<Subjects> subjects;
    public Address address;
}
cassiomolin
  • 124,154
  • 35
  • 280
  • 359
Richa Gupta
  • 143
  • 3
  • 10

1 Answers1

2

You could use valueToTree(). It is functionally similar to serializing value into JSON and parsing JSON as tree, but more efficient.

ObjectNode tree = mapper.valueToTree(foo);
cassiomolin
  • 124,154
  • 35
  • 280
  • 359