簡體   English   中英

如何將JSON參數映射到Jersey參數?

[英]How do I map JSON parameters to Jersey parameters?

我整天都在努力,試圖將一個非常簡單的JSON請求綁定到使用Jersey的方法。 我似乎找不到任何問題,非常感謝您的幫助。

我的JSON請求很簡單:

{"user":"xyz","pwd":"123"}

我的澤西班級看起來像這樣:

@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請求設置為String(user =“ {\\” user \\“:\\” xyz \\“,\\” pwd \\“ :\\“ 123 \\”}“),而pwd保持為空。

我嘗試使用@QueryParam和@FormParam以及“ user”和“ pwd”兩個注釋,但找不到Jersey將JSON值綁定到Java參數的方法。

關於我在做什么錯的任何想法?

謝謝!

您可以使用低級JSONObject或創建自己的Class來接受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();
    }
}

```

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM