可能重複:
Different names of JSON property during serialization and deserialization傑克遜未命名的字段我多麼希望
我在我的網站創建一個選項字符串使用傑克遜與製圖工具,預計JSON使用。因此,舉例來說,我有一個
public class Chart {
Integer zIndex = 3;
public Integer getZIndex() {
return zIndex;
}
}
所以後來我用傑克遜的objectMapper我的圖表上,其輸出是{「Z-索引」:3}在我的問題是,繪圖工具將不接受「Z-索引」,但堅持在駱駝上載入「zIndex」。 我能做些什麼才能在輸出中正確命名? 我試過@JsonProperty(「zIndex」),但是這會在輸出,zindex和zIndex中產生兩個副本,這是令人困惑和醜陋的。另外,如果這有所作爲,我正在使用lombok來生成我的getters。
我想:
public class FieldNamingStrategy extends PropertyNamingStrategy {
@Override
public String nameForField(MapperConfig<?> config, AnnotatedField field, String defaultName) {
return field.getName();
}
}
,然後 objectMapper.setPropertyNamingStrategy()
但這並沒有工作。
我的配置看起來像
String json = null;
StringWriter stringWriter = new StringWriter();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
//TODO: figure this out
objectMapper.setPropertyNamingStrategy(new FieldNamingStrategy());
try {
final JsonGenerator jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(stringWriter);
jsonGenerator.useDefaultPrettyPrinter();
objectMapper.writeValue(jsonGenerator, object);
json = stringWriter.toString();
有關兩種解決方案的替代方法,請參閱:http://stackoverflow.com/questions/8560348/different-names-of-json-property-during-serialization-and-deserialization – pb2q 2012-08-01 21:00:44
「ObjectMapper」配置是什麼樣的? – ggreiner 2012-08-01 22:04:58