如何在Jersey Rest中以JSON格式发送响应 [英] How to send response as JSON in Jersey Rest

查看:305
本文介绍了如何在Jersey Rest中以JSON格式发送响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Jersey Rest Web服务的服务器端代码为

I have Jersey Rest Webservice with server side code as

    @GET
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public List<Employee> getEmployees()
    {
        return new EmployeeService().getEmployees();
    }

T 我正在测试chrome rest客户端的服务. 这可以正常工作 接受:application/xml **但是当我用代码请求时 接受:application/json

T I am testing the service from chrome rest client. This works fine with Accept: application/xml ** But when I am requesting this with code Accept: application/json

我收到以下异常:-

javax.servlet.ServletException:

javax.servlet.ServletException:

org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=application/json, type=class com.rshekhar.domain.Employee, genericType=class com.rshekhar.domain.Employee.

这样做的正确方法是什么.

What is the correct way of doing this.

推荐答案

您可以使用Jersey内置的Jackson JSON库来自动序列化来自任何POJO类的JSON.您只需要将Jackson JSON库添加到pom.xml:

You can use Jersey's built-in Jackson JSON library to automatically serialize JSON from any POJO classes. You just need to add Jackson JSON library to your pom.xml:

    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-json</artifactId>
        <version>${jersey.version}</version>
    </dependency>

此外,为了激活Jersey的POJO映射,您需要在web.xml中添加以下行:

Also in order to activate the POJO mapping of Jersey, you need to add the following lines in web.xml:

    <init-param>
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
        <param-value>true</param-value>
    </init-param>

然后,如果您的类方法EmployeeService().getEmployees()返回员工列表,Jersey会将其序列化为类似(JSON数组)的内容

Then if your class method EmployeeService().getEmployees() returns a list of employees, Jersey will serialize it to something like (JSON array)

{"employees": ["name":"Adam", "name":"Robert", ....]} 

这篇关于如何在Jersey Rest中以JSON格式发送响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆