在 Jersey 服务中使用 JSON 对象对象、Jersey、JSON

2023-09-06 15:04:18 作者:一个人的自由

我一直在谷歌搜索,试图找出如何做到这一点:我有一个 Jersey REST 服务.调用 REST 服务的请求包含一个 JSON 对象.我的问题是,从 Jersey POST 方法实现中,我如何才能访问 HTTP 请求正文中的 JSON?

I've been Googling my butt off trying to find out how to do this: I have a Jersey REST service. The request that invokes the REST service contains a JSON object. My question is, from the Jersey POST method implementation, how can I get access to the JSON that is in the body of the HTTP request?

任何提示、技巧、示例代码的指针将不胜感激.

Any tips, tricks, pointers to sample code would be greatly appreciated.

谢谢...

--史蒂夫

推荐答案

我不确定你会如何获取 JSON 字符串本身,但你当然可以获取它包含的数据,如下所示:

I'm not sure how you would get at the JSON string itself, but you can certainly get at the data it contains as follows:

定义一个带有 JAXB 注释的 Java 类 (C),它与请求中传递的 JSON 对象具有相同的结构.

Define a JAXB annotated Java class (C) that has the same structure as the JSON object that is being passed on the request.

例如对于 JSON 消息:

e.g. for a JSON message:

{
  "A": "a value",
  "B": "another value"
}

使用类似的东西:

@XmlAccessorType(XmlAccessType.FIELD)
public class C
{
  public String A;
  public String B;
}

然后,您可以在资源类中定义一个带有 C 类型参数的方法.当 Jersey 调用您的方法时,将基于 POSTed JSON 对象创建 JAXB 对象.

Then, you can define a method in your resource class with a parameter of type C. When Jersey invokes your method, the JAXB object will be created based on the POSTed JSON object.

@Path("/resource")
public class MyResource
{
  @POST
  public put(C c)
  {
     doSomething(c.A);
     doSomethingElse(c.B);
  }
}