1

I'm using Jackson 1.9.1 from Scala to marshall objects to JSON. My marshalling code looks like this:

val mapper = new ObjectMapper()

mapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, true)
mapper.setPropertyNamingStrategy(new PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy())

val introspectorPair = new AnnotationIntrospector.Pair(
  new JacksonAnnotationIntrospector(),
  new JaxbAnnotationIntrospector()
)
mapper.getSerializationConfig().withAnnotationIntrospector(introspectorPair)

val writer = mapper.defaultPrettyPrintingWriter
writer.writeValueAsString(this)

A typical JSON this is producing looks like this:

{
  "SalesOrder" : {
    "id" : "3187e7d0-f84f-11e0-be50-0800200c9a66",
    "total_paid" : 8.99,
    "created_at" : "2011-05-14T00:00:00.000+0300",
    "updated_at" : "2011-05-14T00:00:00.000+0300"
  }
}

My question is: how do I rename the root key from "SalesOrder" to a more JavaScript-friendly "sales_order"? Adding a JsonProperty override above my class definition doesn't work - presumably because the root key isn't strictly a property (hence also setPropertyNamingStrategy() not being applied either)?

Any guidance on how to achieve this gratefully received!

Alex Dean
  • 14,975
  • 11
  • 61
  • 73

1 Answers1

4

You can either use JAXB annotation @XmlRootElement (when using JaxbAnnotationIntrospector, which you are here), or Jackson's own @JsonRootName (in org.codehaus.jackson.map.annotate1).

Or, if you wanted to do this without annotations, could also sub-class one of AnnotationIntrospector and override findRootName(...) method -- this is what figures out name to use, typically from annotations, but you could implement whatever custom logic you want.

StaxMan
  • 108,392
  • 32
  • 202
  • 235