Jettison作为JSON提供程序
您可能也有兴趣阅读此RESTEasy + Jettison + JAXB示例。
许多人喜欢Jackson JSON处理器 ,它在RESTEasy中受支持。 在本教程中,我们向您展示如何将对象转换为JSON格式并将其返回给客户端。
1. RESTEasy +杰克逊
要将Jackson与RESTEasy集成,您只需包含“ resteasy-jackson-provider.jar ”。
注意
当RESTEasy返回json输出时,它将使用Jackson提供程序自动将其转换。 您无需编写任何代码即可将两者集成。
档案:pom.xml
<repositories>
<repository>
<id>JBoss repository</id>
<url>https://repository.jboss.org/nexus/content/groups/public-jboss/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
<version>2.2.1.GA</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson-provider</artifactId>
<version>2.2.1.GA</version>
</dependency>
</dependencies>
2.简单对象
一个简单的对象,稍后将其转换为JSON格式。
package com.mkyong.rest;
public class Product {
String name;
int qty;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
}
3. JAX-RS
用@Produces("application/json")
注释该方法。 RESTEasy将使用Jackson提供程序来自动处理JSON转换。
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
@Path("/json/product")
public class JSONService {
@GET
@Path("/get")
@Produces("application/json")
public Product getProductInJSON() {
Product product = new Product();
product.setName("iPad 3");
product.setQty(999);
return product;
}
@POST
@Path("/post")
@Consumes("application/json")
public Response createProductInJSON(Product product) {
String result = "Product created : " + product;
return Response.status(201).entity(result).build();
}
}
您必须禁用RESTEasy自动扫描,并手动注册REST服务,否则,将出现此错误 。 希望它在将来的版本中得到修复。
档案:web.xml
<!-- disabled auto scan
<context-param>
<param-name>resteasy.scan</param-name>
<param-value>true</param-value>
</context-param> -->
<context-param>
<param-name>resteasy.resources</param-name>
<param-value>com.mkyong.rest.JSONService</param-value>
</context-param>
4.演示
请参阅GET和POST方法。
1. GET方法
当请求URI模式“ / json / product / get ”时,将返回以下JSON文件。
{
"qty":999,
"name":"iPad 3"
}
2. POST方法
您可以将json格式的字符串“发布”到URI模式“ / json / product / post ”,它将自动转换为“产品”。
下载源代码
下载它– JAX-RS-Download-JSON-Jackson-Example.zip (8 KB)
参考文献
翻译自: https://mkyong.com/webservices/jax-rs/integrate-jackson-with-resteasy/