使用Marshaller将Java对象转换为Json

使用Marshaller将java对象转换为XML非常容易。 但我需要单独使用marshaller将java对象转换为JSON。 我知道使用gson或Xstream就好了。但我需要使用Marshaller。如何实现它?

提前致谢。

注意:我是EclipseLink JAXB(MOXy)的负责人,也是JAXB(JSR-222)专家组的成员,

下面是如何使用MOXy作为JAXB提供程序的方法。

JAVA模型

顾客

import java.util.*; import javax.xml.bind.annotation.*; @XmlRootElement(namespace="http://www.example.com") @XmlType(namespace="http://www.example.com") @XmlAccessorType(XmlAccessType.FIELD) public class Customer { @XmlAttribute private int id; @XmlElement(namespace="http://www.example.com") private String firstName; @XmlElement(namespace="http://www.example.com", nillable=true) private String lastName; @XmlElement(namespace="http://www.example.com") private List phoneNumbers = new ArrayList(); } 

电话号码

 import javax.xml.bind.annotation.*; @XmlAccessorType(XmlAccessType.FIELD) public class PhoneNumber { @XmlAttribute private String type; @XmlValue private String number; } 

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 

演示代码

input.xml中

   Jane  555-1111  

演示

在下面的演示代码中,我们将使用相同的JAXB元数据将XML文档转换为Java对象,然后将这些对象转换回JSON。 使用MOXy,您可以通过在Marshaller上设置属性来指定JSON输出。

 import java.io.File; import javax.xml.bind.*; import org.eclipse.persistence.jaxb.MarshallerProperties; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(Customer.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); File xml = new File("src/forum15357366/input.xml"); Customer customer = (Customer) unmarshaller.unmarshal(xml) ; Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json"); marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false); marshaller.marshal(customer, System.out); } } 

JSON输出

下面是JSON输出。 请注意,没有与命名空间或XML属性对应的指示符。 另请注意,大小为1的集合正确表示为JSON数组(其他一些方法存在问题)。

 { "id" : 123, "firstName" : "Jane", "lastName" : null, "phoneNumbers" : [ { "type" : "work", "value" : "555-1111" } ] } 

JsonMarshaller是一个Java 1.5库,它允许JSON对象与Java对象进行编组和解组。 该项目的目标首先是易用性,透明度和静态类型安全性。 例

如果您有以下Java类:

JAVA:

 @Entity class Book { @Value private String title; @Value private String isbn; @Value private Set authors; } @Entity class Author { @Value private String firstName; @Value private String lastName; } 

并且你创建了一个新的Book()并用它可以编组的信息填充它:

 JSON: {title: "java", isbn: "122333", authors: [{firstName: "Herbert", lastName: "Shield"}, {firstName: "Pascal", lastName: "Perez"}]}