Jackson-自定义序列化程序,仅覆盖特定字段

Jackson-自定义序列化程序,仅覆盖特定字段,第1张

Jackson-自定义序列化程序,仅覆盖特定字段

我遇到了同样的问题,并使用CustomSerializerFactory解决了这个问题。

这种方法使您可以忽略所有对象或特定类型的某些特定字段

public class EntityCustomSerializationFactory extends CustomSerializerFactory {    //ignored fields    private static final Set<String> IGNORED_FIELDS = new HashSet<String>( Arrays.asList(         "class",         "value",         "some" )    );    public EntityCustomSerializationFactory() {        super();    }    public EntityCustomSerializationFactory(Config config) {        super(config);    }    @Override    protected void processViews(SerializationConfig config, BeanSerializerBuilder builder) {        super.processViews(config, builder);        //ignore fields only for concrete class        //note, that you can avoid or change this check        if (builder.getBeanDescription().getBeanClass().equals(Entity.class)){ //get original writer List<BeanPropertyWriter> originalWriters = builder.getProperties(); //create actual writers List<BeanPropertyWriter> writers = new ArrayList<BeanPropertyWriter>(); for (BeanPropertyWriter writer: originalWriters){     String propName = writer.getName();     //if it isn't ignored field, add to actual writers list     if (!IGNORED_FIELDS.contains(propName)){         writers.add(writer);     } } builder.setProperties(writers);        }    }}

然后,您可以使用如下所示的内容:

objectMapper.setSerializerFactory(new EntityCustomSerializationFactory());objectMapper.writevalueAsString(new Entity());//response will be without ignored fields


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5131623.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-17
下一篇 2022-11-17

发表评论

登录后才能评论

评论列表(0条)

保存