我的代码:

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); ... ...

我想要的是在这里添加一个新属性,字符串标识符=“ someValue”;
我想将此属性(在某些条件下)添加到序列化的json中。

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

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


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

最佳答案

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

从您的代码中,我看到了

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);
        }
    }

10-08 07:13