笔记:Jersey REST 传输格式-JSON

JSON 类型已经成为Ajax技术中数据传输的实际标准,Jersey 提供了多种处理JSON数据的包和解析方式,下表展示了JSON包和解析方式:

解析方式\JSON支持包

MOXy

JSON-P

Jackson

基于POJO的JSON绑定

基于JAXB的JSON绑定

低级的(逐字的)JSON解析和处理

  1. 使用 MOXy 处理JSON

    MOXy EclipseLink项目的一个模块,是使用JAXB和SDO作为XML绑定的技术基础,实现了JSR222标准(JAXB2.2)和JSR235标准(SDO2.11),使用MOXy的Java开发者能够高效的完成Java类和XML绑定,所要的只是使用注解来定义他们之间的关系,同时,MOXy实现了JSR-353标准(Java API for Processing JSON1.0),以JAXB为基础来实现对JSR353的支持

  • 定义依赖

    <dependency>

              <groupId>org.glassfish.jersey.media</groupId>

              <artifactId>jersey-media-moxy</artifactId>

    </dependency>

  • 定义Application

    // 该注解用于Servlet3

    @ApplicationPath("/api/*")

    public class JsonResourceConfig extends ResourceConfig {

            public JsonResourceConfig() {

                     register(MyResource.class);

    // 注册JSON处理

    register(MOXyJsonProvider.class);

            property(CommonProperties.MOXY_JSON_FEATURE_DISABLE, Boolean.TRUE);

                     System.out.println("JsonResourceConfig 构造函数调用");

            }

    }

  • Servlet配置(Servlet3 可以不定义web.xml配置)

    <?xml version="1.0" encoding="UTF-8"?>

    <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

                      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

            <servlet>

                    <servlet-name>Jersey Web Application</servlet-name>

                    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>

                    <init-param>

                            <param-name>javax.ws.rs.Application</param-name>

                            <param-value>org.drsoft.rest.JsonResourceConfig</param-value>

                    </init-param>

                    <load-on-startup>1</load-on-startup>

            </servlet>

            <servlet-mapping>

                    <servlet-name>Jersey Web Application</servlet-name>

                    <url-pattern>/*</url-pattern>

            </servlet-mapping>

    </web-app>

  • REST服务代码

        @GET

        @Path ("book")

        @Produces (MediaType.APPLICATION_JSON)

        @Consumes (MediaType.APPLICATION_JSON)

        public Book getBook() {

                Book newBook = new Book();

                newBook.setId(1);

                newBook.setName("Java RESTful WebService学习");

   

                Publisher newPublisher = new Publisher();

                newPublisher.setName("机械出版社");

                newPublisher.setIsbn("989797397342343");

                newPublisher.setPublishTime(new Date());

                newBook.setPublisher(newPublisher);

   

                return newBook;

        }

其中Book类和Publisher类不需要额外处理,MOXy可以根据POJO类来进行JSON绑定,如果需要使用 JAXB 注解本身可以控制一定 JSON 格式输出,具体来说,直接通过使用 JAXB 注释很容易做到重命名(@XmlElement)和删除(@XmlTransient)属性,示例代码如下:

@XmlRootElement

public class Publisher {

        @XmlElement (name = "n")

        private String name;

        private String isbn;

        private Date publishTime;

        @XmlTransient

        public Date getPublishTime() {

                return publishTime;

        }

        public void setPublishTime(Date publishTime) {

                this.publishTime = publishTime;

        }

// setter getter 方法

}

JSON输出内容如下:

{

        "n": "机械出版社",

        "isbn": "989797397342343"

}

   

  1. 使用JSON-P处理JSON

    JSON-P的全称是Java API for JSON Processing(Java 的JSON处理API),是JSR353标准规范,用于统一Java处理JSON格式数据的API,其生产和消费的JSON数据以流的形式处理,并为JSON数据建立Java对象模型。

  • 定义依赖

    <dependency>

                <groupId>org.glassfish.jersey.media</groupId>

                <artifactId>jersey-media-json-processing</artifactId>

    </dependency>

  • 定义Application

    // 该注解用于Servlet3

    @ApplicationPath("/api/*")

    public class JsonProcessingResourceConfig extends ResourceConfig {

            public JsonProcessingResourceConfig() {

                    // 注册REST类

                    register(MyResource.class);

                    // 启用格式化Json数据的输出

                    property(JsonGenerator.PRETTY_PRINTING, Boolean.TRUE);

            }

    }

  • Servlet配置(Servlet3 可以不定义web.xml配置)

    <?xml version="1.0" encoding="UTF-8"?>

    <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

                      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

            <servlet>

                    <servlet-name>Jersey Web Application</servlet-name>

                    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>

                    <init-param>

                            <param-name>javax.ws.rs.Application</param-name>

                            <param-value>org.drsoft.rest.JsonProcessingResourceConfig</param-value>

                    </init-param>

                    <load-on-startup>1</load-on-startup>

            </servlet>

            <servlet-mapping>

                    <servlet-name>Jersey Web Application</servlet-name>

                    <url-pattern>/*</url-pattern>

            </servlet-mapping>

    </web-app>

  • REST服务代码

        @GET

        @Path ("bookJsonP")

        @Produces (MediaType.APPLICATION_JSON+";charset=UTF-8")

        @Consumes (MediaType.APPLICATION_JSON)

        public JsonObject getBookByJsonP() {

   

                JsonObjectBuilder publisherObjectBuilder = Json.createObjectBuilder();

                publisherObjectBuilder.add("isbn", "939393939393939");

                publisherObjectBuilder.add("name", "电子工程也出版社");

                publisherObjectBuilder.add("publishTime", new Date().toString());

   

                JsonObjectBuilder objectBuilder = Json.createObjectBuilder();

                objectBuilder.add("name", "Java RESTful WebService学习");

                objectBuilder.add("id", 999);

                objectBuilder.add("publisher", publisherObjectBuilder);

   

                return objectBuilder.build();

        }

JSON-P不需要创建POJO类,通过JsonObjectBuilder来创建JsonObject对象,通过该对象输出Json字符串。

   

   

posted @ 2017-06-30 22:25  立3807  阅读(2021)  评论(0编辑  收藏  举报