如何使用BeanSerializerModifier的changeProperties添加新属性?

时间:2016-09-06 17:43:49

标签: java json serialization jackson

我的代码:

private class CustomBeanSerializerModifier extends BeanSerializerModifier{ @Override public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc,List<BeanPropertyWriter> beanProperties){ List<BeanPropertyWriter> beanPropertiesToIgnore = new ArrayList<>(); if (!CollectionUtils.isEmpty(fieldSettingsMap)) { for (int i = 0; i < beanProperties.size(); i++) { BeanPropertyWriter beanPropertyWriter = beanProperties.get(i); ... ...

我想要的是在这里添加一个新属性,例如,String identifier =&#34; someValue&#34 ;; 我希望将此属性(有一些条件)添加到序列化的json。

BeanPropertyWriter的唯一构造函数需要很多参数:

new BeanPropertyWriter(propDef, member, contextAnnotations, declaredType, ser, typeSer, serType, suppressNulls, suppressableValue)

我可以在这里添加新房产吗? 如果是的话,我应该在这里传递给构造函数的值是什么?

1 个答案:

答案 0 :(得分:1)

不是一种简单的方法,但您可以尝试以下

从你的代码中,我看到了这个

BeanPropertyWriter beanPropertyWriter = beanProperties.get(i);

使用新属性的复制构造函数创建此beanPropertyWriter的副本(使用以下方式,因为原始构造函数受到保护,因此不可见)

// Use this to create a copy of the old property, and change name to new name
    BeanPropertyWriter newBeanPropertyWriter = new CustomBeanPropertyWriter(beanPropertyWriter,"newFieldName");

        public class CustomBeanPropertyWriter extends BeanPropertyWriter {
                protected CustomBeanPropertyWriter(BeanPropertyWriter base, String newFieldName) {
                    super(base, new SerializedString(newFieldName));
                }
            }

这将使用复制构造函数来更改字段名称。

不确定值部分,但似乎_field保持不变。 您可以通过调试器检查值来自哪个字段并相应地更改它。 比方说,如果_field保存了值,那么这可能会有效吗?

public class CustomBeanPropertyWriter extends BeanPropertyWriter {

        protected Field setField(Field newValue){
            super._field = newValue;
        }

        protected CustomBeanPropertyWriter(BeanPropertyWriter base, String newFieldName, Field newFieldValue) {
            super(base, new SerializedString(newFieldName));
            setField(newFieldValue);
        }
    }