在Jersey服务中使用JSON对象 [英] Consuming JSON object in Jersey service

查看:88
本文介绍了在Jersey服务中使用JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在搜寻我的屁股,试图找出如何做到这一点:我有一个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消息:

{
  "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);
  }
}

这篇关于在Jersey服务中使用JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆