![](/img/trans.png)
[英]Jackson: how to wrap object with a key, which is one of the properties of serialized object?
[英]How to include only certain properties and fields of my object to be serialized by Jackson?
我有一个class需要序列化,它包含了很多属性和字段,但是我只需要序列化一小部分,而不是整个class。我也想保证以后不会不小心添加字段这将被序列化并打破我对突然包含新内容的序列化内容的期望。
那么我可以使用任何注释来基本上指定仅序列化的内容吗?
我需要与@JsonIgnoreProperties 相反的东西。 充当白名单而不是黑名单的东西。
尚未对此进行测试,但您应该能够禁用 JsonAutoDetect,然后手动注释每个属性。
没有这样的注释,您必须在@JsonIgnoreProperties
的属性上使用@JsonIgnoreProperties
。
您可以从您的班级中介绍一个新班级。
MyClass
你原来的班级
MyClassForJson
具有您选择的属性的类的MyClassForJson
。
仅将第二类用于序列化。 也许您可以在序列化之前进行转换。 这样你的 json 就不会发生意外的变化。
到目前为止,我更喜欢使用包装器对象来实现这种白名单效果(在我的情况下,额外的复杂性是我想要选择性地序列化的 POJO 是对象层次结构的一部分,因此无法使用视图)。
如果MyClass
是原始类而MyClassForJson
是包装器,我就是这样使用它的:
public class MyClassForJson {
private MyClass wrapped;
public MyClassForJson(MyClass toBeWrapped) {
this.wrapped = toBeWrapped;
}
/**
* Delegate method exposing a property
*/
public String getExposedProperty() {
return this.wrapped.getExposedProperty();
}
}
现在,只有我为其创建委托 getter 方法的属性在序列化时才会暴露给 Jackson,无论我向MyClass
添加了多少属性。 目前,大多数 IDE 可以为包装类的选定属性自动生成委托方法。
如果我想使用不同的白名单属性以不同的方式序列化MyClass
,我所要做的就是创建不同的包装类。
我能够使用@JsonView
注释使其工作。
用于指示被注释的方法或字段定义的属性所属的视图的注释。
您可以将任何类用于视图,但我更喜欢在一个位置创建它们:
public class JsonViews {
public static class Small {}
public static class Medium extends Small {}
}
然后在课堂上:
public class User {
@JsonView(JsonViews.Small.class)
private Integer id;
@JsonView(JsonViews.Medium.class)
private String name;
// email does not have a view, by default it will be in any view
private String email;
...
}
然后我们可以将视图类传递给ObjectMapper
mapper.writerWithView(clazz);
如果您不希望在 JSON 中定义没有视图的属性,请确保配置ObjectMapper
mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);
这是一个老问题,但如果有人仍在寻找答案:
您正在搜索的功能是从 2.12 版开始实现的,称为 @JsonIncludeProperties。
对于想要为特定 class 执行此操作的任何人。
正如另一个答案中指出的那样, @JsonAutoDetect
注释就是这种方式。
然后使用@JsonProperty
注释您想要的属性,以将它们包含在序列化中。
下面的示例,如果您像我一样使用 lombok 或其他“吸气剂生成”工具,请注意boolean
属性的isGetterVisibility = Visibility.NONE
参数。
@JsonAutoDetect(getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE)
public class MyClass {
@JsonProperty
private String id;
//list of properties without @JsonProperty, which will not be serialized
}
@JsonAutoDetect
有更多选项,请参阅文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.