使用类元数据序列化JSON

huangapple go评论76阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年9月30日 16:35:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/64133860.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定