Deserializing json containing a long string is slow but doing it in two steps is fast

Viewed 384

I have a JsonNode type object containing a json structure that has an embedded file, as an encoded base64 string, in it. This Json is supposed to get deserialized to a Java object. The Object looks something like:

Public class Info implements Serializable {

 private String detail;
 private Int count;

 // Other fields
 private List<Attachment> attachments;
  
 //Getters and Setter

}

Public class Attachment implements Serializable {
 private String fileName;
 private String data;

 //Getters and Setters
}

In this case the original file size is about 300 kb (above 394000 characters in base64 format).

I have this statement for deserialization which read a type JsonNode and converts it to Info

 jsonNode = anotherObject.getJsonNodeField();
 ObjectMapper mapper = new ObjectMapper();
 Info info = mapper.treeToValue(jsonNode, Info.class);

The above works but the process takes more than 1500 milli seconds. Through many trials and errors, I figured the following approach improves the process significantly.

//Get the attachments and then remove it from the jsonNode
JsonNode attachmentsJson = jsonNode.findValue("attachments");
((ObjectNode)jsonNode).remove("attachments");
//Deserialize to Info Object 
Info info = mapper.treeToValue(jsonNode, Info.class);
ObjectReader reader = new ObjectReader().readFor(new TypeReference<List<Attachment>>(){});
//Deserialize attachments
List<Attachment> attachments = reader.readValue(attachmentsJson);
//Join things together
info.setAttachments(attachments);

Doing the two step deserialization makes the whole process very fast down to below 400 milliseconds. I do not know why the second approach gives me a superior performance unlike the first approach. My guess is that it has something to do with memory. I Was wondering if somebody could guide me on this to get a better understanding. Thanks.

0 Answers
Related