注意:我是EclipseLink JAXB (MOXy) 的负责人,也是JAXB (JSR-222) 专家组的成员。
对于这个用例,您可以使用 MOXy 提供的 JSON 绑定。
域模型(根)
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
int number;
String string;
}
将 MOXy 指定为 JSON 绑定提供程序
在 RESTful 环境中,您可以将 MOXyJsonProvider 指定为您的 JAX-RS 应用程序的 MessageBodyReader/MessageBodyWriter
在下面的独立示例中,您可以使用以下条目在与域模型相同的包中指定 jaxb.properties 文件(请参阅:http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html):
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
演示代码
下面是一个独立的示例,您可以运行它来证明一切正常:
import java.util.*;
import javax.xml.bind.*;
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[] {Root.class}, properties);
Root root = new Root();
root.number = 1234;
root.string = "1234";
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);
}
}
输出
下面是运行演示代码的输出:
{
"number" : 1234,
"string" : "1234"
}