读书人

EclipseLink Moxy对最新java api for

发布时间: 2013-08-11 22:22:29 作者: rapoo

EclipseLink Moxy对最新java api for json(JSR-353)的实现
最新的jave ee 7中,对JSON的解析实现使用的是JSR-353,其中,Eclipse旗下的EclipseLink开源项目向JAVE EE 7中贡献了不少力量,其中包括JPA 2.1 (JSR-338)的实现,另外一个贡献是本文向大家介绍的EclipseLink MOXy项目,它是JAVE EE 7中JAX-RS(REST标准)的一个默认的JSON Provider.
首先简单介绍下Eclipse旗下的EclipseLink开源项目,它主要用来实现快速将JAVA中的对象转化为各种类型的XML,该项目主要有如下的特性:

支持JAXB中最多的注解
同时支持XML和JSON
支持最新的JPA 2.1
对JPA-RS的增强支持

 MOXY有十分强大的将各类JAVA对象 序列化为XML以及XML反序列化为JAVA对象的能力。这在REST架构的应用中,MOXY可以用来实现JAX-RS标准中的各种转换,

下面选用一个例子大致讲解下,首先是一个jaxb声明的pojo,如下

import java.io.FileInputStream;import java.util.*;import javax.json.*;import javax.xml.bind.*;import org.eclipse.persistence.jaxb.JAXBContextProperties;import org.eclipse.persistence.oxm.json.JsonStructureSource;public class UnmarshalDemo {    public static void main(String[] args) throws Exception {        try (FileInputStream is = new FileInputStream("src/blog/jsonp/moxy/input.json")) {                    Map<String, Object> jaxbProperties = new HashMap<String, Object>(2);            jaxbProperties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");            jaxbProperties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);            JAXBContext jc = JAXBContext.newInstance(new Class[] {Customer.class},                 jaxbProperties);            Unmarshaller unmarshaller = jc.createUnmarshaller();            // Parse the JSON            JsonReader jsonReader = Json.createReader(is);            // Unmarshal Root Level JsonArray            JsonArray customersArray = jsonReader.readArray();            JsonStructureSource arraySource = new JsonStructureSource(customersArray);            List<Customer> customers =                 (List<Customer>) unmarshaller.unmarshal(arraySource, Customer.class)                .getValue();            for(Customer customer : customers) {                System.out.println(customer.getFirstName());            }            // Unmarshal Nested JsonObject            JsonObject customerObject = customersArray.getJsonObject(1);            JsonStructureSource objectSource = new JsonStructureSource(customerObject);            Customer customer = unmarshaller.unmarshal(objectSource, Customer.class)                .getValue();            for(PhoneNumber phoneNumber : customer.getPhoneNumbers()) {                System.out.println(phoneNumber.getNumber());            }        }    }}


输入的JSON:
[
{
"id":1,
"firstName":"Jane",
"lastName":null,
"phoneNumbers":[
{
"type":"cell",
"number":"555-1111"
}
]
},
{
"id":2,
"firstName":"Bob",
"lastName":null,
"phoneNumbers":[
{
"type":"work",
"number":"555-2222"
},
{
"type":"home",
"number":"555-3333"
}
]
}
]

输出结果:

Jane


2 Bob


3 555-2222


4 555-3333
同时可以参考偶的译文:
http://developer.51cto.com/art/201306/399778.htm

读书人网 >JavaScript

热点推荐