有没有办法使用Jackson JSON处理器进行自定义字段级序列化?例如,我想要上课
public class Person {
public String name;
public int age;
public int favoriteNumber;
}
Run Code Online (Sandbox Code Playgroud)
序列化为以下JSON:
{ "name": "Joe", "age": 25, "favoriteNumber": "123" }
Run Code Online (Sandbox Code Playgroud)
注意,age = 25被编码为数字而favoriteNumber = 123被编码为字符串.开箱即用杰克逊编组int了一个号码.在这种情况下,我希望favoriteNumber被编码为字符串.
我想序列化一个不受我控制的POJO类,但是想要避免序列化来自超类的任何属性,而不是来自最终类.例:
public class MyGeneratedRecord extends org.jooq.impl.UpdatableRecordImpl<...>,
example.generated.tables.interfaces.IMyGenerated {
public void setField1(...);
public Integer getField1();
public void setField2(...);
public Integer getField2();
...
}
Run Code Online (Sandbox Code Playgroud)
您可以从示例中猜测此类是由JOOQ生成的,并且继承自复杂的基类UpdatableRecordImpl,该类还具有一些类似于bean属性的方法,这会在序列化期间导致问题.此外,我有几个类似的类,所以最好避免为我生成的所有POJO重复相同的解决方案.
到目前为止,我找到了以下可能的解决方案:
使用mixin技术忽略来自超类的特定字段,如下所示:如何告诉jackson忽略我无法控制源代码的属性?
这个问题是如果基类发生变化(例如,新的getAnything()方法出现在它中),它可能会破坏我的实现.
实现自定义序列化程序并在那里处理问题.这对我来说似乎有点矫枉过正.
顺便说一下,我有一个接口,它描述了我想要序列化的属性,也许我可以混合一个@JsonSerialize(as = IMyGenerated.class)注释......?我可以将此用于我的目的吗?
但是,从纯粹的设计角度来看,最好的方法是告诉杰克逊我只想序列化最终类的属性,并忽略所有继承的属性.有没有办法做到这一点?
提前致谢.
我尝试了一些我在搜索时发现的东西,但没有任何帮助,或者我没有正确实现它.
我得到的错误
Direct self-reference leading to cycle (through reference chain: io.test.entity.bone.Special["appInstance"]->io.test.entity.platform.ApplicationInstance["appInstance"])
Run Code Online (Sandbox Code Playgroud)
这两个都扩展了基本实体,并且在基础(超类)中也有它appInstance.
基本实体看起来与此类似
@MappedSuperclass
public abstract class BaseEntity implements Comparable, Serializable {
@ManyToOne
protected ApplicationInstance appInstance;
//getter & setter
}
Run Code Online (Sandbox Code Playgroud)
应用程序实体如下所示
public class ApplicationInstance extends BaseEntity implements Serializable {
private List<User> users;
// some other properties (would all have the same base and application instance . User entity will look similar to the Special.)
}
Run Code Online (Sandbox Code Playgroud)
特殊实体
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "objectType")
@JsonIgnoreProperties({"createdBy", "appInstance", "lastUpdatedBy"}) …Run Code Online (Sandbox Code Playgroud)