Search code examples
javajsonjacksonobjectmapper

Jackson Objectmapper on value of field?


I am using Jackson ObjectMapper to convert to JSON string. I want to use a PropertyNamingStrategy so that my fields can be given different names.

Ex: attribute ---> attr, name --> nm

OBJECT MAPPER:---> JSON STRING:
{
  "attribute" : [ {
    "name" : "accessPolicyIDs",
    "value" : "R400"
  }, {
    "name" : "maxOfInstances",
    "value" : "10"
  } ]
}

I can achieve this as by following class:

public class LongNameShortNameNamingStrategy extends PropertyNamingStrategyBase {

    @Override
    public String translate(String propertyName) {

        String shortName = null;
        shortName = LongNameShortNames.getShortName(propertyName);
        if (shortName != null){
            return shortName;
        }

        return propertyName;
    }
}

However, now there is a requirement to convert the value inside name attribute to short name too. Ex: accessPolicyIDs --> acp, maxOfInstances --> mxi

How can this be achieved ?? Can ObjectMapper be configured to work on value of a particular field??


Solution

  • You can try create custom ValueSerializer. Something like:

    public class CustomValueSerializer extends JsonSerializer<String> {
    
       @Override
       public void serialize(String s, JsonGenerator jsonGenerator,
                             SerializerProvider serializerProvider) throws IOException {    
    
           if(jsonGenerator.getOutputContext().getCurrentName().equals("name")){
              s = getShortName(s);
           }
           jsonGenerator.writeString(s);
       }
    
       @Override
       public Class<String> handledType() {
           return String.class;
       }
    
       private String getShortName(String s){
          //make string short
       }
    }
    

    To use this serializer, add it to mapper:

    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.addSerializer(new CustomValueSerializer());
    mapper.registerModule(module);
    String jsonString = mapper.writeValueAsString(person);
    

    Also, if you have access to pojo, you can mark Name property with annotation:

    @JsonProperty
    @JsonSerialize(using = CustomValueSerializer.class)
    public String getName(){
      return name;
    }