代码之家  ›  专栏  ›  技术社区  ›  Steve

在Jersey服务中使用JSON对象

  •  33
  • Steve  · 技术社区  · 16 年前

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

    --Steve

    7 回复  |  直到 16 年前
        1
  •  16
  •   pestrella    13 年前

    @Consumes text/plain

    假设您的客户必须将JSON发布到API,但需要将Content-Type头指定为 Content-Type: application/json .

    String MessageBodyReader .这样做同样容易,而且您不必在API规范上妥协。

    MessageBodyReader

    MessageBodyReader

    @Provider
    @Consumes("application/json")
    public class CustomJsonReader<T> implements MessageBodyReader<T> {
      @Override
      public boolean isReadable(Class<?> type, Type genericType,
          Annotation[] annotations,MediaType mediaType) {
        return true;
      }
    
      @Override
      public T readFrom(Class<T> type, Type genericType, Annotation[] annotations,
          MediaType mediaType, MultivaluedMap<String, String> httpHeaders,
          InputStream entityStream) throws IOException, WebApplicationException {
    
        /* Copy the input stream to String. Do this however you like.
         * Here I use Commons IOUtils.
         */
        StringWriter writer = new StringWriter();
        IOUtils.copy(entityStream, writer, "UTF-8");
        String json = writer.toString();
    
        /* if the input stream is expected to be deserialized into a String,
         * then just cast it
         */
        if (String.class == genericType)
          return type.cast(json);
    
        /* Otherwise, deserialize the JSON into a POJO type.
         * You can use whatever JSON library you want, here's
         * a simply example using GSON.
         */
        return new Gson().fromJson(json, genericType);
      }
    }

    Type genericType ).如果是这样,那么只需将JSON转换为指定的 type ).如果预期的类型是某种POJO,则使用JSON库(例如Jackson或GSON)将其反序列化为POJO。

    MessageBodyReader

    MessageBodyReader

    JerseyServletModule

    bind(CustomJsonReader.class).in(Scopes.SINGLETON);

    以上 CustomJsonReader 物体。

    @POST
    @Path("/stuff")
    @Consumes("application/json") 
    public void doStuff(String json) {
      /* do stuff with the json string */
      return;
    }
        2
  •  14
  •   Andres Peter Centgraf    9 年前

    Jersey支持使用Jettyon类型JSONObject和JSONArray对解析的JSONObject进行低级访问。

    <dependency>
        <groupId>org.codehaus.jettison</groupId>
        <artifactId>jettison</artifactId>
        <version>1.3.8</version>
    </dependency>
    

    {
      "A": "a value",
      "B": "another value"
    }
    
    
    @POST
    @Path("/")
    @Consumes(MediaType.APPLICATION_JSON) 
    public void doStuff(JSONObject json) {
      /* extract data values using DOM-like API */
      String a = json.optString("A");
      Strong b = json.optString("B");
      return;
    }
    

    Jersey documentation

        3
  •  12
  •   Andy    16 年前

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

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

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

    @Path("/resource")
    public class MyResource
    {
      @POST
      public put(C c)
      {
         doSomething(c.A);
         doSomethingElse(c.B);
      }
    }
    
        4
  •  7
  •   Will    14 年前

    @POST
    @Path("/")
    @Consumes("text/plain") 
    @Produces(MediaType.APPLICATION_JSON)
    public String processRequset(String pData) {
        // do some stuff, 
        return someJson;
    }
    
        5
  •  0
  •   doyle doyle    16 年前

    公共解析json(jsonString)

        6
  •  0
  •   Whome    6 年前

    一些答案说服务功能必须使用 consumes=text/plain application/json jackson-core=2.6.1, jersey-common=2.21.0 .

    @POST
    @Path("/{name}/update/{code}")
    @Consumes({ "application/json;charset=UTF-8" })
    @Produces({ "application/json;charset=UTF-8" })
    public Response doUpdate(@Context HttpServletRequest req, @PathParam("name") String name, 
          @PathParam("code") String code, String reqBody) {
      System.out.println(reqBody);
    
      StreamingOutput stream = new StreamingOutput() {
        @Override public void write(OutputStream os) throws IOException, WebApplicationException {
          ..my fanzy custom json stream writer..
        }
      };
    
      CacheControl cc = new CacheControl();
      cc.setNoCache(true);
      return Response.ok().type("application/json;charset=UTF-8")
        .cacheControl(cc).entity(stream).build();
    }
    

    应用程序/json