我已经使用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可能的问题是什么?
发布于 2013-03-14 18:29:23
注意:我是的负责人,也是专家组的成员。
JAXB (JSR-222)规范不包括JSON绑定。您可以使用提供原生EclipseLink绑定的JSON (MOXy),而不是使用带有丢弃库的JAXB实现。下面是一个例子。
JAVA模型
Foo
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演示代码
演示
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/Output
我们看到在输入或输出中没有根元素。
{
"mylist" : [ {
"id" : 104,
"name" : "Only one found"
} ]
}附加信息
发布于 2013-03-14 14:46:52
只需阅读@XmlRootElement并不总是必要的。请阅读this blog,在底部你会发现在没有@XmlRootElement的情况下是如何做到的。也可以通过帖子No @XmlRootElement generated by JAXB中的答案。
https://stackoverflow.com/questions/15402659
复制相似问题