0

Possible Duplicate:
Different names of JSON property during serialization and deserialization

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

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.

I tried:

public class FieldNamingStrategy extends PropertyNamingStrategy {

@Override
public String nameForField(MapperConfig<?> config, AnnotatedField field, String defaultName) {
    return field.getName();
}

}

and then 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();

Community
  • 1
  • 1
newmanne
  • 2,019
  • 5
  • 22
  • 31
  • 1
    For two solution alternatives, see: http://stackoverflow.com/questions/8560348/different-names-of-json-property-during-serialization-and-deserialization – pb2q Aug 01 '12 at 21:00
  • what does your `ObjectMapper` configuration look like? – driangle Aug 01 '12 at 22:04

1 Answers1

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.

Or if you can not do that, just add @JsonProperty annotation to BOTH getter and field.

Your main problem is really that name itself is "non-compliant", meaning that pieces might not match.

StaxMan
  • 113,358
  • 34
  • 211
  • 239