在java REST中解析JSON参数时出错
我最近升级了RESTAPI以使用jersey 2。现在我无法像以前那样检索JSON body参数,这些方法不再被调用。我的猜测是,我缺少一个将JSON解析为java对象的依赖项,但我不太确定需要添加什么,希望您能提供帮助
pom。xml
<dependencies>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.19</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.19</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.19</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>2.22</version>
</dependency>
</dependencies>
休息方法
@POST
@Path("/users/{userId}/friends")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response followUser(@PathParam("userId") Integer myUserId, FollowUserBean user) {}
FollowUserBean。java
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class FollowUserBean {
public Integer friendId;
public FollowUserBean() {}
}
# 1 楼答案
你需要一个JSON提供者
在撰写本文时,泽西岛2号。x与以下模块集成以提供JSON支持:
利用杰克逊
请参阅下面使用Jackson作为Jersey 2的JSON提供程序所需的步骤。x:
添加模块依赖项
使用杰克逊2。作为JSON提供者,您需要将^{} 模块添加到
pom.xml
文件中:使用Jackson 1。它看起来像:
注册Jackson模块
除了添加上述依赖项之外,还需要在^{} /^{} 子类中注册^{} (或^{} for Jackson 1.x):
如果没有^{} /^{} 子类,可以在} 。可以在^{} 初始化参数的逗号分隔值中提供特定的资源、提供者和功能完全限定类名
web.xml
部署描述符中注册^{杰克逊提供的^{} 是^{}
有关更多详细信息,请查看Jersey documentation关于支持常见媒体类型表示的文章
# 2 楼答案
您可能缺少Jersey JSON Jackson(2.x)实体提供程序支持模块:
建议在所有LIB中使用相同的Jersey版本