英文:
Serializing JSON with class metadata
问题
我曾经使用过Gson和Jackson,它们都提供了处理多态性的方法。例如,使用Jackson时,您需要使用@JsonSubTypes
声明类,并添加每个@JsonSubTypes.Type
。类似的事情也会在Gson中发生。
我的问题是是否有一种选项使其像MongoDB序列化数据的方式一样工作。它会自动添加一个_class
元数据字段。使用这种方法,您不需要手动注册每个子类型。
这种可能吗?
英文:
I've used both Gson and Jackson and both of them offer a way to deal with polymorphism. For example, with Jackson you need to declare the class with a @JsonSubTypes
and add each and every @JsonSubTypes.Type
you have. Similar thing happens with Gson.
My question is if there is an option to make it work like with how MongoDB serializes data. It automatically adds a _class
metadata field. With this method, you don't need to manually register every subtype you've created.
Is it possible?
答案1
得分: 5
你可以使用 Jackson 实现这个功能:
@JsonTypeInfo(use = Id.CLASS, include = As.PROPERTY, property = "_class")
public abstract class AbstractModel {
}
public class ModelA extends AbstractModel {
}
...
mapper.writeValue(System.out, new ModelA());
输出结果:
{
"_class" : "demo.ModelA"
}
这样,您无需为添加的所有类型添加 JSON 子类型。
英文:
You can achieve this with jackson:
@JsonTypeInfo(use = Id.CLASS, include = As.PROPERTY, property = "_class")
public abstract class AbstractModel {
}
public class ModelA extends AbstractModel {
}
...
mapper.writeValue(System.out, new ModelA());
Outputs:
{
"_class" : "demo.ModelA"
}
This way you dont have to add json subtypes for all types you add.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论