基于它与Jackson或Gson实现的一个接口对类进行序列化 [英] Serialize class based on one interface it implements with Jackson or Gson
问题描述
接口I1扩展Ia,Ib,Ic
接口I2 。
一个C类实现了I1,I2。
$ b C cInstance = new C():
// Jackson
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File(somefile.json),cInstance);
// Gson
Gson gson = new Gson();
String json = gson.toJson(cInstance);
输出将根据C的属性及其继承的内容进行cInstance序列化。
但是,我喜欢将这些属性序列化为根据I1中的setter / getters(仅在I1接口中表示的cInstance属性)。
我如何做到这一点与杰克逊知道我有太多的类具有相同的问题,我不能修改类定义或添加注释。
而同样的问题适用于反序列化(按照界面反序列化)
谢谢 解决方案
首先,即使不直接添加注释,您也可以随时添加混合注释(请参见 wiki页面)。有了这个,使用的注释将是:
$ p $ @JsonSerialize(as = MyInterface.class)
但如果您不想使用混入,您可以强制使用特定类型
objectMapper.typedWriter(MyInterface.class).writeValue(....)
I have the following:
An interface I1 extends Ia, Ib, Ic
An interface I2.
A class C implements I1, I2. And this class has its own setters and getters as well.
C cInstance = new C():
//Jackson
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("somefile.json"), cInstance);
//Gson
Gson gson = new Gson();
String json = gson.toJson(cInstance);
The output will be cInstance serialized according to the properties of C and what it inherited. However, I like the properties are being serialized to be according to the setters/getters in I1 (only the cInstance properties represented in the I1 interface).
How can I do this with Jackson knowing that I have too many classes with the same problem and I can't modify the class definition or add annotations.
And the same issue applies to Deserialization (Deserializing according to an interface)
Thanks
First of all, you can always attach "mix-in annotations" even without adding annotations directly (see wiki page). With this, annotation to use would be:
@JsonSerialize(as=MyInterface.class)
but if you do not want to use mix-ins, you can force specific type to use with
objectMapper.typedWriter(MyInterface.class).writeValue(....)
这篇关于基于它与Jackson或Gson实现的一个接口对类进行序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!