如何使用Java Jackson重命名JSON的根密钥? [英] How do I rename the root key of a JSON with Java Jackson?

查看:112
本文介绍了如何使用Java Jackson重命名JSON的根密钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Scala的Jackson 1.9.1来将对象编组为JSON。我的编组代码如下所示:

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)

这产生的典型JSON如下所示:

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"
  }
}

我的q uestion是:如何将根密钥从SalesOrder重命名为更适合JavaScript的sales_order?在我的类定义上面添加 JsonProperty 覆盖不起作用 - 可能是因为根密钥不是严格的属性(因此也是 setPropertyNamingStrategy()还没有应用)?

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!

推荐答案

你可以使用JAXB注释 @XmlRootElement (使用JaxbAnnotationIntrospector时,你在这里),或杰克逊自己的 @JsonRootName (在 org.codehaus.jackson.map.annotate1 中)。

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).

或者,如果你想在没有注释的情况下这样做,也可以将AnnotationIntrospector中的一个子类化并覆盖 findRootName(...)方法 - 这就是数字要使用的名称,通常来自注释,但您可以实现您想要的任何自定义逻辑。

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.

这篇关于如何使用Java Jackson重命名JSON的根密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆