Quiero convertir el mapa a json pero cambiando el caso usando jackson. Por ejemplo, tengo este mapa:
"test_first" -> 1, "test_second" -> 2,Quiero convertirlo a json pero cambiando de guión bajo a minúsculasCamelCase. ¿Cómo puedo hacer eso? Usar esto no ayudó:
// 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);Utilice la anotación @JsonProperty . Sobre su variable de propiedad o sobre su getter, haga esto:
@JsonProperty("testFirst") String test_first; @JsonProperty("testSecond") String test_second; Aparentemente, también puede usar las anotaciones @JsonGetter y @JsonSetter como alternativa. Lea sobre esto en Jackson Annotation Examples areticle
Hay StringKeySerializer en Jackson que puede implementar la funcionalidad para cambiar la presentación de las claves en algún mapa (por ejemplo, usando 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> { }Luego, el mapa se serializa con el formato requerido:
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}