gpt4 book ai didi

java - 通过 Jettison 将 Java 对象(没有 @XmlRootElement)编码为 JSON

转载 作者:行者123 更新时间:2023-11-30 09:25:15 26 4
gpt4 key购买 nike

我已经使用 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

可能是什么问题?

最佳答案

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

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

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

演示代码

演示

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

附加信息

关于java - 通过 Jettison 将 Java 对象(没有 @XmlRootElement)编码为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15402659/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com