1

I read through this post Jackson: deserializing null Strings as empty Strings which has this cool trick

mapper.configOverride(String.class)
  .setSetterInfo(JsonSetter.Value.forValueNulls(Nulls.AS_EMPTY));

THEN on the flipside, I read through this post Jackson serialization: ignore empty values (or null) which has this cool trick

objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

This is VERY VERY close except I really don't want incoming data to be null in any case. I have the following code printing 4 situations with the above settings BUT want to fix the null piece so any json we unmarshal into java results in

public class MapperTest {
    private static final Logger log = LoggerFactory.getLogger(MapperTest.class);

    private ObjectMapper mapper = new ObjectMapper();
    public MapperTest() {
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        mapper.configOverride(String.class)
                .setSetterInfo(JsonSetter.Value.forValueNulls(Nulls.AS_EMPTY));
    }

    public static void main(String[] args) throws JsonProcessingException {
        new MapperTest().start();
    }

    private void start() throws JsonProcessingException {
        //write out java color=null resulting in NO field...
        String val = mapper.writeValueAsString(new Something());
        log.info("val="+val);

        Something something = mapper.readValue(val, Something.class);
        log.info("value='"+something.getColor()+"'");

        //write out java color="" resulting in NO field...
        Something s = new Something();
        s.setColor("");
        String val2 = mapper.writeValueAsString(new Something());
        log.info("val="+val2);

        String temp = "{\"color\":null,\"something\":0}";
        Something something2 = mapper.readValue(temp, Something.class);
        log.info("value2='"+something2.getColor()+"'");
    }
}

The output is then

    INFO: val={"something":0}
    INFO: value='null'
    INFO: val={"something":0}
    INFO: value2=''

NOTE: The value = 'null' is NOT what I desire and want that to also be empty string. Notice that if customers give a color:'null', it does result in empty string. Non-existence should result in the same thing for us "". This is a HUGE win in less mistakes in this area 'for us' I mean. thanks, Dean

Matthew Zhang
  • 58
  • 1
  • 5

0 Answers0