serialization - 如何序列化 JsonNode
问题描述
我将以下实例保存到 Aerospike 数据库。我要序列化的课程
public class School implements Serializable {
private static final long serialVersionUID = 1L;
private JsonNode studentInfo;
private JsonNode teacherInfo;
private void writeObject(ObjectOutputStream out) throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue((OutputStream) out, studentInfo);
mapper.writeValue((OutputStream) out, teacherInfo);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
ObjectMapper mapper = new ObjectMapper();
this.studentInfo = mapper.readValue((InputStream) in, JsonNode.class);
this.teacherInfo = mapper.readValue((InputStream) in, JsonNode.class);
}
}
使用上面的代码,保存到数据库工作正常(序列化)。
但是当我尝试从数据库(反序列化)中获取数据时,我面临以下异常。
Caused by: com.aerospike.client.AerospikeException$Serialize: Error -10,1,30000,0,5,BB95B2FFB6EA79A 10.66.29.66 3030: ***com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input***
at [Source: java.io.ObjectInputStream@6ff29830; line: 1, column: 0]
at com.aerospike.client.command.Buffer.bytesToObject(Buffer.java:341)
at com.aerospike.client.command.Buffer.bytesToParticle(Buffer.java:69)
如果我遗漏了什么,请告诉我。
解决方案
我认为我们不能多次使用 ObjectOutputStream 和 ObjectInputStream。我通过编写writeObject和readObject函数解决了它。
private void writeObject(ObjectOutputStream out) throws IOException {
ObjectMapper mapper = new ObjectMapper();
ArrayNode arrayNode = mapper.createArrayNode().add(this.studentInfo).add(this.teacherInfo);
mapper.writeValue((OutputStream) out, arrayNode);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
ObjectMapper mapper = new ObjectMapper();
ArrayNode arrayNode = null;
arrayNode = mapper.readValue((InputStream) in, ArrayNode.class);
this.studentInfo = arrayNode.studentInfo;
this.teacherInfo = arrayNode.teacherInfo;
}
或者您可以创建一个具有 2 个字段的 POJO 作为 JsonNode 并序列化 POJO。
推荐阅读
- c# - 如何在 WPF 中绑定多个嵌套属性
- javascript - 从其他函数状态 REACTJS 获取 api 调用的值
- sql - 用于拆分电子邮件的sql查询
- c++ - SWIG_exception() prints SWIG_RuntimeError as string
- javascript - How to add text to end of each array element using map?
- ruby-on-rails - 页面未在 heroku 上显示 - heroku [路由器]:状态 = 500
- javascript - javascript中事件的'x'和'clientX'属性之间的区别
- android - Adapter.getView Kotlin android 的参数 convertView 上的 IllegalArgumentException
- python - Python 3 - Google Drive API: AttributeError: 'Resource' object has no attribute 'children'
- angular - ng-container 上的组件