JAXB删除XmlRootElement包装器 [英] JAXB remove XmlRootElement wrapper

查看:59
本文介绍了JAXB删除XmlRootElement包装器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个@XmlRootElement类Person.

    @XmlRootElement
    class Person {
        private String desc;
    }

,返回内容为

    {"Person": {"desc": "abc"} }

我真的不想要根包装,所以我希望内容看起来像

    {"desc": "abc"}

我可以通过JaxB完成此操作吗?如果是这样,怎么办?谢谢!

解决方案

JAXB是XML的API,而不是JSON.

但是,有一些可以利用JAXB注释的JSON库(至少是Jackson).我不知道您使用的是哪一个,所以我也不知道该如何最好地提供帮助. (如果将其与Jersey框架一起使用,它将使用Jackson进行JSON序列化.)您将需要配置要使用的任何JSON库,以便能够在JSON输出中配置根元素的包装". /p>

我写了这个快速的Groovy脚本来在Jackson中进行测试:

@Grab('com.fasterxml.jackson.core:jackson-databind:2.2.2')
import javax.xml.bind.annotation.XmlRootElement
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializationFeature

@XmlRootElement
public class Person {
  public String desc = "howdy"
}

Person p = new Person()
ObjectMapper om = new ObjectMapper().enable(SerializationFeature.WRAP_ROOT_VALUE)
println om.writeValueAsString(p)

如上所述,它输出JSON:

{"Person":{"desc":"howdy"}}

如果您取出零件.enable(SerializationFeature.WRAP_ROOT_VALUE),它将为您提供:

{"desc":"howdy"}

因此,如果您正在使用Jackson,则好像在幕后使用的ObjectMapper设置为WRAP_ROOT_VALUE,而您只需要关闭它即可.

I have this @XmlRootElement class Person.

    @XmlRootElement
    class Person {
        private String desc;
    }

and the return content is

    {"Person": {"desc": "abc"} }

and I really don't want the root wrapper, so I want the content to looks like

    {"desc": "abc"}

Can I accomplish this via JaxB? If so, how? Thanks!

解决方案

JAXB is an API for XML, not JSON.

However, there are some JSON libraries (at least Jackson) which can utilize JAXB annotations. I don't know which one you are using, so I don't know exactly how to best help. (If you are using this with the Jersey framework, it uses Jackson for its JSON serialization.) You will need to configure whatever JSON library you are using to be able to configure the "wrapping" of the root element in the JSON output.

I wrote up this quick Groovy script to test this in Jackson:

@Grab('com.fasterxml.jackson.core:jackson-databind:2.2.2')
import javax.xml.bind.annotation.XmlRootElement
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializationFeature

@XmlRootElement
public class Person {
  public String desc = "howdy"
}

Person p = new Person()
ObjectMapper om = new ObjectMapper().enable(SerializationFeature.WRAP_ROOT_VALUE)
println om.writeValueAsString(p)

As it is written above, it outputs the JSON:

{"Person":{"desc":"howdy"}}

If you take out the part .enable(SerializationFeature.WRAP_ROOT_VALUE) it gives you:

{"desc":"howdy"}

So if you are using Jackson, it looks like the ObjectMapper that is being used behind the scenes is being set to WRAP_ROOT_VALUE and you just need to turn that off.

这篇关于JAXB删除XmlRootElement包装器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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