我正在尝试根据父 bean 的信息有条件地序列化子 bean。
public class Parent {
private boolean isSecure;
private Child child;
}
public class Child {
String someValue;
}
基本上,如果 parent.isSecure()
为真,那么我想以不同于 parent.isSecure()
的方式序列化 someValue
> 是错误的。
我的实际类比这个简单的例子复杂得多,所以我真的不想为我需要单独维护的 Parent
创建一个完整的自定义序列化程序(除非你能告诉我如何在自定义序列化程序中利用 Parent
的标准序列化,而不必遍历所有属性并处理 JSON 注释、 View 等。如果可以,那可能会起作用,因为我可以设置一个基于 isSecure()
的上下文属性。
我不介意为子级编写自定义序列化程序,但我不知道如何检查父级的值。
我考虑过使用“安全” View 和“不安全” View ,我可以在整个序列化过程之外指定它们,但是我必须仔细检查并注释父类的许多属性“安全”和“不安全” View (因为我关闭了 DEFAULT_VIEW_INCLUSION
选项,因为我不想序列化许多属性)。
我尝试在我的自定义子序列化程序中访问 generator.getCurrentValue()
,但它始终为空,所以我不确定它应该如何工作。
我考虑过为 isSecure
编写一个自定义序列化程序,并在其中设置一个上下文属性,但我如何才能确定它会在子项的自定义序列化程序之前被调用? (尽管我承认我不确定上下文属性是否真的按照我假设的方式工作。)
有什么想法吗?
最佳答案
您可以创建一个特定于您的 isSecure
的序列化程序设想。使用 JsonGenerator#getCurrentValue
子元素内部将返回父元素。像这样的东西应该允许你控制 Child
的序列化无需修改 Parent
上其他属性的序列化.
创建一个Child
序列化程序检查 Parent
属性(property)
SecureChildSerializer
和 InsecureChildSerializer
应该是 JsonSerializer<Child>
的实现
public class IsSecureChildSerializer extends JsonSerializer<Child> {
private static final SecureChildSerializer SECURE_CHILD_SERIALIZER = new SecureChildSerializer();
private static final InsecureChildSerializer INSECURE_CHILD_SERIALIZER = new InsecureChildSerializer();
@Override
public void serialize(Child value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
if (gen.getCurrentValue() instanceof Parent) {
Parent parent = (Parent) gen.getCurrentValue();
if (parent.isSecure) {
SECURE_CHILD_SERIALIZER.serialize(value, gen, serializers);
} else {
INSECURE_CHILD_SERIALIZER.serialize(value, gen, serializers);
}
}
}
}
应用Child
关注属性的序列化程序
public class Parent {
public boolean isSecure;
@JsonSerialize(using = IsSecureChildSerializer.class)
public Child child;
}
关于java - 基于父上下文的自定义 Jackson JSON 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31034850/