我一整天都在努力,尝试将一个非常简单的 JSON 请求绑定(bind)到使用 Jersey 的方法。我似乎找不到问题所在,非常感谢任何帮助。
我的 JSON 请求就像这样简单:
{"user":"xyz","pwd":"123"}
我的 Jersey 类如下所示:
@Path("/rest")
public class JerseyService {
@POST
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
@Consumes(MediaType.APPLICATION_JSON)
@Path("authenticate.svc")
@Transactional(readOnly = true)
public Response authenticate(
String user,
String pwd) throws IOException {
Response.ResponseBuilder responseBuilder = Response.ok();
responseBuilder.entity(JsonSerializer.serialize(Status.SUCCESS));
return responseBuilder.build();
}
}
当我按原样将 JSON 请求发送到服务时,“user”参数将整个 JSON 请求设置为字符串(user = "{\"user\":\"xyz\",\"pwd\":\"123\"}"),而 pwd 保持为空。
我尝试过使用 @QueryParam、@FormParam 以及其他带有“user”和“pwd”的注释,但我找不到 Jersey 将 JSON 值绑定(bind)到 Java 参数的方法。
对我做错了什么有什么想法吗?
谢谢!
最佳答案
您可以使用低级 JSONObject 或创建自己的类来接受 json 参数。 以下是 JSONObject 的示例。
```
@Path("/rest")
public class JerseyService {
@POST
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
@Consumes(MediaType.APPLICATION_JSON)
@Path("authenticate.svc")
@Transactional(readOnly = true)
public Response authenticate(final JSONObject login) throws IOException {
System.out.println(login.getString("user"));
System.out.println(login.getString("pwd"));
//^^^^^^^^^^^^^^^^^
Response.ResponseBuilder responseBuilder = Response.ok();
responseBuilder.entity(JsonSerializer.serialize(Status.SUCCESS));
return responseBuilder.build();
}
}
```
关于java - 如何将 JSON 参数映射到 Jersey 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21762888/