通过Jettison将Java对象(不带@XmlRootElement)编组到JSON

时间:2013-03-14 06:30:45

标签: java json java-ee jaxb jettison

我已经使用Jettison将JAXB对象(包含@XmlRootElement)编组到JSON。但我无法将没有@XmlRootElement等注释的简单java对象转换为JSON。我想知道"是否必须让@XmlRootElement将对象编组为JSON?"

当我尝试将java对象编组为Json

时,我收到以下异常
com.sun.istack.SAXException2: unable to marshal type "simpleDetail" as an element because it is missing an @XmlRootElement annotation

可能是什么问题?

2 个答案:

答案 0 :(得分:1)

注意:我是EclipseLink JAXB (MOXy)主管,是JAXB (JSR-222)专家组的成员。

JAXB(JSR-222)规范不包括JSON绑定。您可以使用提供本机JSON绑定的EclipseLink JAXB(MOXy),而不是使用Jettison库的JAXB实现。以下是一个例子。

JAVA模型

<强>富

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
public class Foo {

    private List<Bar> mylist;

}

<强>酒吧

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
public class Bar {

    private int id;
    private String name;

}

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

DEMO CODE

<强>演示

MOXy不需要@XmlRootElement注释,您可以使用JSON_INCLUDE_ROOT属性告诉MOXy忽略任何@XmlRootElement注释的存在。忽略根元素时,您需要使用unmarshal方法,该方法使用类参数指定要解组的类型。

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[] {Foo.class}, properties);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        StreamSource json = new StreamSource("src/forum15404528/input.json");
        Foo foo = unmarshaller.unmarshal(json, Foo.class).getValue();

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

}

<强> input.json /输出

我们发现输入或输出中没有根元素。

{
   "mylist" : [ {
      "id" : 104,
      "name" : "Only one found"
   } ]
}

其他信息

答案 1 :(得分:0)

请注意,@XmlRootElement并非总是必要的。请阅读this blog,您可以在底部找到没有@XmlRootElement的情况。 另请查看帖子No @XmlRootElement generated by JAXB中的答案。