杰克逊映射到 json 改变大小写

Jackson map to json with changing case

我想将地图转换为 json,但要使用 jackson 更改大小写。例如,我有这张地图:

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

我想将其转换为 json,但要从下划线大小写更改为 lowerCamelCase。我怎么做?使用这个没有帮助:

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

使用@JsonProperty注释。在您的 属性 变量或其 getter 上执行此操作:

@JsonProperty("testFirst")
String test_first;

@JsonProperty("testSecond")
String test_second;

显然您也可以使用 @JsonGetter@JsonSetter 注释作为替代。在 Jackson Annotation Examples 文章

中了解它

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> {
}

然后将地图序列化为所需格式:

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}