欢迎光临
我们一直在努力

使用Jersey构建RESTful服务之将Java对象转换为Json并输出

请先看汇总篇「Web Service入门及实践」,学习前面的基础知识和例子再来看这篇!

在使用Web Service时,Json是经常用到的数据交换格式。这个例子就是演示如何将Java对象转换为Json格式,并返回给Web Service客户端。

首先增加一个实体类User:

package com.demo3.bean;

import javax.xml.bind.annotation.XmlRootElement;

/**
 * 用户实体类
 * <p>
 * XmlRootElement表示将bean转换为xml,用在实体类中,
 * 如果要将bean以xml或json的格式返回,必须要这个注解
 */
@XmlRootElement
public class User {
    private String userId;
    private String userName;
    private String age;

    public User() {
    }

    public User(String userId, String userName, String age) {
        this.userId = userId;
        this.userName = userName;
        this.age = age;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}

然后增加一个resource

package com.demo3.resources;

import com.demo3.bean.User;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Path("/userJson")
public class UserJsonResource {
    private static Map<String, User> userMap = new HashMap<String, User>();//存储用户

    @GET
    @Path("/allUsersJson")
    @Produces(MediaType.APPLICATION_JSON)
    public List<User> getAllUsers() {
        List<User> users = new ArrayList<User>();
        User u1 = new User("001", "Michael", "26");
        User u2 = new User("002", "King", "23");
        User u3 = new User("003", "Susan", "21");

        userMap.put(u1.getUserId(), u1);
        userMap.put(u2.getUserId(), u2);
        userMap.put(u3.getUserId(), u3);

        users.addAll(userMap.values());
        return users;
    }

    @GET
    @Path("/singleUserJson")
    @Produces(MediaType.APPLICATION_JSON)
    public User getUserXml() {
        User user = new User();
        user.setAge("21");
        user.setUserId("004");
        user.setUserName("Michael");
        return user;
    }
}

这个resource,实现了两个功能,allUsersJson返回多个用户的json,singleUserJson返回单个用户的json。

但是,执行到这一步,如果你直接在浏览器访问http://localhost:8080/jerseydemo/rest/userJson/allUsersJsonhttp://localhost:8080/jerseydemo/rest/userJson/singleUserJson,浏览器会报501错误,后台会报错:

严重: MessageBodyWriter not found for media type=application/json, type=class java.util.ArrayList, genericType=java.util.List<com.demo3.bean.User>.

这是因为项目中还没有加入对json的转换支持。具体操作maven用户直接引入jackson的jar包依赖:

<!-- JAX-RS -->
        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>javax.ws.rs-api</artifactId>
            <version>${jaxrs.version}</version>
        </dependency>
        <!-- Jersey 2.26 -->
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>${jersey2.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>${jersey2.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-client</artifactId>
            <version>${jersey2.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.inject</groupId>
            <artifactId>jersey-hk2</artifactId>
            <version>${jersey2.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
            <version>${jersey2.version}</version>
        </dependency>
    </dependencies>

然后在web.xml里进行配置:

<!--配置Jersey RESTful服务-->
    <servlet>
        <servlet-name>Jersey REST Service</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>
                com.demo1.resources
                com.demo2.resources
                com.demo3.resources
            </param-value>
        </init-param>
        <init-param>
            <param-name>jersey.config.server.provider.classnames</param-name>
            <param-value>org.glassfish.jersey.jackson.JacksonFeature</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey REST Service</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

接下来再去访问就可以了。

结果截图

AllUsersJson.jpg

源码

移步「Github-jerseydemo-demo3」

参考文章:

  1. 用Jersey构建RESTful服务3–JAVA对象转成JSON输出
  2. Jersey 2.0 equivalent to POJOMappingFeature
赞(0)
未经允许不得转载:Ddmit » 使用Jersey构建RESTful服务之将Java对象转换为Json并输出

评论 抢沙发

登录

找回密码

注册