xml - JAXB 删除 XmlRootElement 包装器

标签 xml json jaxb marshalling jaxb2

我有这个@XmlRootElement 类 Person。

    @XmlRootElement
    class Person {
        private String desc;
    }

返回内容为

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

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

    {"desc": "abc"}

我可以通过 JaxB 完成吗?如果是这样,如何?谢谢!

最佳答案

注意:我是 EclipseLink JAXB (MOXy) JAXB (JSR-222) 的领导和成员专家组。

作为answered by esseplymale JAXB (JSR-222) 涵盖 XML 而不是 JSON 绑定(bind)。然而,JAXB 在这个空间中经常直接使用(JAXB impl 与 Jettison 之类的东西一起使用,将 JSON 转换为 StAX 事件,请参阅:http://blog.bdoughan.com/2011/04/jaxb-and-json-via-jettison.html)和间接使用(解释 JAXB 注释子集的 JSON 绑定(bind)实现)。

下面是您如何通过利用 EclipseLink MOXy 作为您的 JAXB 提供者来完成您的用例。

Java 模型

下面是您问题中的 Person 类。我添加了 @XmlAccessorType(XmlAccessType.FIELD) 注释,这样我就可以避免添加访问器方法(参见:http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html)。

import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
class Person {

    private String desc;

}

jaxb.properties

您使用 MOXy 作为您的 JAXB 提供程序,您需要在与您的域模型相同的包中包含一个名为 jaxb.properties 的文件,并包含以下条目(请参阅:http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html)。

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

演示代码

演示

演示代码中有几点需要注意:

  1. JAXBContextProperties.MEDIA_TYPE 属性用于将 MOXy 置于 JSON 绑定(bind)模式。
  2. JAXBContextProperties.JSON_INCLUDE_ROOT 属性用于告诉 MOXy 省略根元素。
  3. 当根元素被省略时,您需要使用带有 Class 参数的 unmarshal 方法之一告诉 MOXy 您要解码的类型。
import java.util.*;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
import org.eclipse.persistence.jaxb.JAXBContextProperties;

public class Demo {

    public static void main(String[] args) throws Exception {
        Map<String, Object> properties = new HashMap<String, Object>(2);
        properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
        properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
        JAXBContext jc = JAXBContext.newInstance(new Class[] {Person.class}, properties);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        StreamSource json = new StreamSource("src/forum18417466/input.json");
        Person person = unmarshaller.unmarshal(json, Person.class).getValue();

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(person, System.out);
    }

}

input.json/输出

{
   "desc" : "abc"
}

关于xml - JAXB 删除 XmlRootElement 包装器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18417466/

相关文章:

r - 在 R 中保存 xml 节点

php - 无法使用 Jquery 获取 JSON 值

python - 遍历 Django 模板中的 json 列表

javascript - 使用 AngularJS 验证单选按钮

jaxb - 使用 binder 解码具有命名空间的 xml 时出现 jaxb moxy 问题

java - 如何使 Sonar 兼容 XMLInputFactory 和 woodstox 库注册的实现?

xml - 我可以重新定义 XSD 架构以更改某个类型的子项的 maxOccurs 属性吗?

java - JAXB 忽略 xml 标记属性

java - JAXB 映射 将复杂对象映射到 JSON

c++ - OS 可移植 C/C++ XML 解析器