1

My Code :

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

What i want is to add a new property here say, String identifier = "someValue"; i want this property to be added(with some condition) to the serialized json.

The only constructor of BeanPropertyWriter takes lot of arguments :

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

Can i add a new property here at all? if yes, what are the values i should pass to the constructor here?

Sachin Sharma
  • 1,446
  • 4
  • 18
  • 37

1 Answers1

1

Not an easy way but you can try the following

From your code, i see this

BeanPropertyWriter beanPropertyWriter = beanProperties.get(i);

Create a copy of this beanPropertyWriter by using the copy constructor for the new property(Use the following way, as the original constructor is protected and hence not visible)

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

This will use the copy constructor to change field Name.

Not sure about the value part but seems that maybe _field holds the same. Could you check via your debugger which field the value comes and change it accordingly. Say for example if _field holds the value then maybe this might work ?

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);
        }
    }
Danyal
  • 448
  • 4
  • 18