【问题标题】:How do I map JSON parameters to Jersey parameters?如何将 JSON 参数映射到 Jersey 参数?
【发布时间】:2014-03-12 20:12:17
【问题描述】:

我整天都在苦苦挣扎,试图将一个非常简单的 JSON 请求绑定到一个使用 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 值绑定到 Java 参数的方法。

对我做错了什么有任何想法吗?

谢谢!

【问题讨论】:

    标签: java json rest jersey


    【解决方案1】:

    您可以使用低级 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();
        }
    }
    

    ```

    【讨论】:

    • 解决了!只需添加 jersey-json 依赖项即可导入 JSONObject。谢谢!
    猜你喜欢
    • 2015-05-09
    • 1970-01-01
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    • 2019-06-24
    • 2015-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多