gpt4 book ai didi

java - 隐藏 Jackson 序列化中的 protected 字段

转载 作者:行者123 更新时间:2023-12-02 02:52:19 25 4
gpt4 key购买 nike

出于某种原因,我无法通过 ObjectMapper 配置隐藏 protected 字段(没有 setter),使其不被序列化为 JSON 字符串。

我的POJO:

public class Item {

protected String sn;
private String name;

public Item(){
sn = "43254667";
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getSn() {
return sn;
}

}

我的映射器:

mapper.setVisibility(PropertyAccessor.SETTER, Visibility.PUBLIC_ONLY);
mapper.setVisibility(PropertyAccessor.GETTER, Visibility.PUBLIC_ONLY);
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.NONE);

输出为:

{
"sn" : "43254667",
"name" : "abc"
}

更新:我无法修改 Item 类,因此无法使用注释。

最佳答案

使用@JsonIgnore

您可以使用 @JsonIgnore 注释字段或方法。

它是一个标记注释,指示基于内省(introspection)的序列化和反序列化功能将忽略带注释的方法或字段。

使用如下:

public class Item {

@JsonIgnore
protected String sn;

...
}

或者如下:

public class Item {

...

@JsonIgnore
public String getSn() {
return sn;
}
}

@JsonIgnore 与 mix-ins 结合使用

基于您的comment ,当无法修改类时,您可以使用混合注释,如 answer 中所述。 .

您可以将其视为一种面向方面的方式,在运行时添加更多注释,以增强静态定义的注释。

首先,定义一个混合注释接口(interface)(类也可以):

public interface ItemMixIn {

@JsonIgnore
String getSn();
}

然后配置您的ObjectMapper使用定义的接口(interface)作为 POJO 的混合:

ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(Item.class, ItemMixIn.class);

有关更多详细信息,请查看documentation .

使用BeanSerializerModifier

基于您的comment ,您可以考虑BeanSerializerModifier ,如下:

public class CustomSerializerModifier extends BeanSerializerModifier {

@Override
public List<BeanPropertyWriter> changeProperties(SerializationConfig config,
BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {

// In this method you can add, remove or replace any of passed properties

return beanProperties;
}
}

然后将自定义序列化器注册为 ObjectMapper 中的模块.

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new SimpleModule() {

@Override
public void setupModule(SetupContext context) {
super.setupModule(context);
context.addBeanSerializerModifier(new CustomSerializerModifier());
}
});

关于java - 隐藏 Jackson 序列化中的 protected 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43605127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com