【发布时间】:2012-07-30 19:32:25
【问题描述】:
可能重复:
Different names of JSON property during serialization and deserialization
我在我的网站上使用 Jackson 创建一个选项字符串,以与需要 JSON 的图表工具一起使用。例如,我有一个
public class Chart {
Integer zIndex = 3;
public Integer getZIndex() {
return zIndex;
}
}
然后我在我的图表上使用 Jackson 的 objectMapper,输出是 {"zindex":3} 我的问题是图表工具不会接受“zindex”,但坚持使用驼峰式的“zIndex”。 我该怎么做才能在输出中正确命名它? 我已经尝试过@JsonProperty("zIndex") 但这会在输出中生成两个副本,zindex 和 zIndex,这令人困惑且丑陋。另外,我正在使用 lombok 来生成我的吸气剂,如果这有影响的话。
我试过了:
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();
【问题讨论】:
-
对于两种解决方案替代方案,请参阅:stackoverflow.com/questions/8560348/…
-
您的
ObjectMapper配置是什么样的?