Home > Back-end >  Jackson map to json with changing case
Jackson map to json with changing case

Time:03-01

I want to convert map to json but with changing case using jackson. For example, I have this map:

 "test_first" -> 1,
 "test_second" -> 2,

I want to convert it to json but with changing from underscore case to lowerCamelCase. How do I do that? Using this didn't help:

// Map<String, String> fields;

var mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE); 
// setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE) didn't help too
String json = mapper.writeValueAsString(fields);

CodePudding user response:

There is StringKeySerializer in Jackson which may implement the functionality to change presentation of the keys in some map (e.g. using Guava CaseFormat):

// custom key serializer
class SnakeToCamelMapKeySerialiser extends StdKeySerializers.StringKeySerializer {
    @Override
    public void serialize(Object value, JsonGenerator g, SerializerProvider provider)
            throws IOException {
        g.writeFieldName(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, (String) value));
    }
}

// map with the custom serializer
@JsonSerialize(keyUsing = SnakeToCamelMapKeySerialiser.class)
class MyMap<K extends String, V> extends HashMap<K, V> {
}

Then the map is serialized with the required format:

Map<String, Integer> map = new MyMap<>();
map.put("first_key", 1);
map.put("second_key", 2);

ObjectMapper mapper = new ObjectMapper();


String json = mapper.writeValueAsString(map);

System.out.println(json);
// -> {"firstKey":1,"secondKey":2}

CodePudding user response:

Use @JsonProperty annotation. Over your property variable or over its getter do this:

@JsonProperty("testFirst")
String test_first;

@JsonProperty("testSecond")
String test_second;

Apparently you can also use @JsonGetter and @JsonSetter annotations as an alternative. Read about it in Jackson Annotation Examples areticle

  • Related