Possible Duplicate:
Different names of JSON property during serialization and deserialization可能重复:序列化和反序列化期间JSON属性的不同名称
I am using Jackson on my site to create an options string to be used with a charting tool that expects JSON. So for example, I have a
我在我的网站上使用Jackson来创建一个选项字符串,用于需要JSON的图表工具。所以,例如,我有一个
public class Chart {
Integer zIndex = 3;
public Integer getZIndex() {
return zIndex;
}
}
so then I use Jackson's objectMapper on my chart and the output is {"zindex":3} where my issue is that the charting tool will not accept "zindex" but insists on the camel cased "zIndex". What can I do to get this to be named properly in the output? I've tried @JsonProperty("zIndex") but this generates two copies in the output, zindex and zIndex, which is confusing and ugly. Also, I am using lombok to generate my getters, if that makes a difference.
所以我在我的图表上使用杰克逊的objectMapper,输出是{“zindex”:3}我的问题是图表工具不接受“zindex”但坚持使用驼峰“zIndex”。我该怎么做才能在输出中正确命名?我已经尝试了@JsonProperty(“zIndex”),但这会在输出中生成两个副本,zindex和zIndex,这是令人困惑和丑陋的。此外,我正在使用lombok来生成我的getter,如果这有所不同。
I tried:
public class FieldNamingStrategy extends PropertyNamingStrategy {
@Override
public String nameForField(MapperConfig<?> config, AnnotatedField field, String defaultName) {
return field.getName();
}
}
and then objectMapper.setPropertyNamingStrategy()
然后是objectMapper.setPropertyNamingStrategy()
but this didn't work.
但这没用。
My configuration looks like
我的配置看起来像
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();
1 个解决方案
#1
0
Make sure you use a modern version of Jackson: 1.9 improved handling of properties, so that annotation would work even when added to just one of pieces.
确保使用现代版本的Jackson:1.9改进了属性处理,这样即使添加到一个部分中,注释也会起作用。
Or if you can not do that, just add @JsonProperty
annotation to BOTH getter and field.
或者如果你不能这样做,只需将@JsonProperty注释添加到BOTH getter和field中。
Your main problem is really that name itself is "non-compliant", meaning that pieces might not match.
你的主要问题是这个名称本身是“不合规”的,这意味着这些名称可能不匹配。
#1
0
Make sure you use a modern version of Jackson: 1.9 improved handling of properties, so that annotation would work even when added to just one of pieces.
确保使用现代版本的Jackson:1.9改进了属性处理,这样即使添加到一个部分中,注释也会起作用。
Or if you can not do that, just add @JsonProperty
annotation to BOTH getter and field.
或者如果你不能这样做,只需将@JsonProperty注释添加到BOTH getter和field中。
Your main problem is really that name itself is "non-compliant", meaning that pieces might not match.
你的主要问题是这个名称本身是“不合规”的,这意味着这些名称可能不匹配。