我有一个JsonNode类型的对象,其中包含一个json结构,该结构中包含一个嵌入式文件(作为编码的base64字符串)。 该Json应该反序列化为Java对象。 对象看起来像:
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
}
在这种情况下,原始文件大小约为300 kb(base64格式超过394000个字符)。
我有这个反序列化语句,它读取JsonNode类型并将其转换为Info
jsonNode = anotherObject.getJsonNodeField();
ObjectMapper mapper = new ObjectMapper();
Info info = mapper.treeToValue(jsonNode, Info.class);
以上方法有效,但是该过程耗时超过1500毫秒。 通过多次试验和错误,我发现以下方法可以显着改善流程。
//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);
执行两步反序列化可使整个过程非常快地降至400毫秒以下。 我不知道为什么第二种方法不像第一种方法那样能为我提供出色的性能。 我的猜测是它与内存有关。 我想知道是否有人可以在这方面指导我以获得更好的理解。 谢谢。