我想將地圖轉換為 json,但使用杰克遜改變大小寫。例如,我有這張地圖:
"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);
uj5u.com熱心網友回復:
在StringKeySerializerJackson 中可以實作更改某些地圖中鍵的表示的功能(例如使用 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}
uj5u.com熱心網友回復:
使用@JsonProperty注釋。在您的屬性變數或其吸氣劑上執行以下操作:
@JsonProperty("testFirst")
String test_first;
@JsonProperty("testSecond")
String test_second;
顯然,您也可以使用@JsonGetter和@JsonSetter注釋作為替代方案。在Jackson 注釋示例文章中閱讀有關它的內容
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/435075.html
