在手册中there is a sample ,仅包含原始情况。
如果我的情况不原始怎么办?
假设我有一个类,它在默认序列化方面存在问题(在我的例子中是无限递归)。
该类包含多个字段,其中一些是“主要”字段并保存信息,而另一些是服务字段。
所以我只需要序列化“主”字段并从中派生服务字段。
class MyType1 {
MyType2 a; // "main" field
MyType3 b; // service fiels
}
class MySerializer implements JsonSerializer<MyType1> {
@Override
public JsonElement serialize(MyType1 arg0, Type arg1, JsonSerializationContext arg2) {
JsonObject ans = new JsonObject();
// ans.add("a", ... // what to write here? How to wrap a into JsonElement?
return ans;
}
}
我知道我可以在这个特定情况下使用transient
关键字。但问题是关于编写序列化器。
更新
我强调使用 transient 并不是一个答案。我的问题是关于自定义序列化器。怎么写?
最佳答案
class MyTypeToSerialize {
MyType2 a; // "main" field
}
class MyType1 extends MyTypeToSerialize {
MyType3 b; // service fiels
}
如果您只想对字段 MyType2 a
进行序列化/反序列化,则使用 MyTypeToSerialize
(您不需要自定义序列化器或反序列化器)
编辑:@Brian Roach 的建议是更好、更简单的解决方案:
class MyType1 {
MyType2 a; // "main" field
transient MyType3 b; // service fiels
}
编辑2:
So I need to serialize only "main" fields and derive service ones from them.
因此请使用上面的建议。
I know I can use transient keyword for this specific case. But the question is about writing serializers.
为什么你认为需要序列化器?
关于java - 一般情况下如何实现JsonSerializer的序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22152018/