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;
}