注意:我是EclipseLink JAXB (MOXy)的负责人,也是JAXB (JSR-222)专家组的成员。
如何构建我的Java对象?
以下是您的对象模型示例。MOXy的JSON绑定利用JAXB注释将域模型映射到JSON,因此我也包括了这些注释。JAXB实现具有默认规则来映射字段/属性名称,但由于您的文档不同于默认值,每个字段都必须进行注释。
MyResult
package forum11001458;
import javax.xml.bind.annotation.*;
@XmlRootElement(name="MyResult")
public class MyResult {
@XmlElement(name="AccountID")
private String accountID;
@XmlElement(name="User")
private User user;
@XmlElement(name="Result")
private Result result;
}
用户
package forum11001458;
import javax.xml.bind.annotation.XmlElement;
public class User {
@XmlElement(name="Name")
private String name;
@XmlElement(name="Email")
private String email;
}
结果
package forum11001458;
import javax.xml.bind.annotation.XmlElement;
public class Result {
@XmlElement(name="Course")
private String course;
@XmlElement(name="Score")
private String score;
}
我应该使用哪个Json库?
以下是如何使用MOXy进行JSON绑定的方法:
jaxb.properties
要使用MOXy作为您的JAXB提供程序,您需要在与域模型相同的包中包含一个名为jaxb.properties
的文件,并包含以下条目:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
演示
请注意,MOXy的JSON绑定不需要任何编译时依赖项。 所有必要的API都可在Java SE 6中使用。 如果您使用的是Java SE 5,则可以添加必要的支持API。
package forum11001458;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(MyResult.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
unmarshaller.setProperty("eclipselink.media-type", "application/json");
File json = new File("src/forum11001458/input.json");
Object myResult = unmarshaller.unmarshal(json);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty("eclipselink.media-type", "application/json");
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(myResult, System.out);
}
}
input.json/Output
{
"MyResult" : {
"AccountID" : "12345",
"User" : {
"Name" : "blah blah",
"Email" : "blah@blah.com"
},
"Result" : {
"Course" : "blah",
"Score" : "10.0"
}
}
}