Note:我是EclipseLink JAXB (MOXy) http://www.eclipse.org/eclipselink/moxy.php领导者和成员JAXB (JSR-222) http://jcp.org/en/jsr/detail?id=222专家组。
As 由 eseplymale 回答 https://stackoverflow.com/a/18421298/383861JAXB (JSR-222) 涵盖 XML 而非 JSON 绑定。然而,JAXB 经常直接使用(JAXB impl 与 Jetison 之类的东西一起使用,以将 JSON 与 StAX 事件相互转换,请参阅:http://blog.bdoughan.com/2011/04/jaxb-and-json-via-jettison.html http://blog.bdoughan.com/2011/04/jaxb-and-json-via-jettison.html)和间接(解释 JAXB 注释子集的 JSON 绑定实现)在此空间中。
以下是您如何利用 EclipseLink MOXy 作为 JAXB 提供程序来完成您的用例。
Java模型
Person
下面是Person
类从你的问题。我已经添加了@XmlAccessorType(XmlAccessType.FIELD)
注释,以便我可以避免添加访问器方法(请参阅:http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html 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.属性
您使用 MOXy 作为 JAXB 提供程序,您需要包含一个名为jaxb.properties
在与域模型相同的包中,包含以下条目(请参阅:http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html).
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
演示代码
Demo
演示代码中有几点需要注意:
- The
JAXBContextProperties.MEDIA_TYPE
属性用于将 MOXy 置于 JSON 绑定模式。
- The
JAXBContextProperties.JSON_INCLUDE_ROOT
属性用于告诉 MOXy 省略根元素。
- 当省略根元素时,您需要使用以下之一告诉 MOXy 您正在解组的类型
unmarshal
方法采用Class
范围。
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);
}
}
输入.json/输出
{
"desc" : "abc"
}