【问题标题】:POST request to Jersey Service对 Jersey 服务的 POST 请求
【发布时间】:2014-02-23 20:24:53
【问题描述】:

我在传递一个 json 对象时尝试调用 post 方法,但是当我打印该对象时,它是未初始化的形式。

我正在做类似的事情 curl -X POST -H 'Content-Type: application/json' -d '{"distributors":{"distributorId":"5","name":"SA"}}' {path}

这是 Java 代码:

package com.rest.resource;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "distributors")
public class Distributor
   {
   @XmlElement
   private long   distributorId;
   @XmlElement
   private String name;

   public Distributor()
      {
      }

   public Distributor(final long distributorId,final String name)
      {
      this.distributorId = distributorId;
      this.name = name;
      }
   @Override
   public String toString()
      {
      return "distributors: {distributorId = " + distributorId + ", name = " + name + "}";
      }
   }

资源中的方法

@POST
   @Path("")
   public Response addDistributor(final JAXBElement<Distributor> element)
      {
      final Distributor distributor = element.getValue();
      System.out.println(distributor);
      return Response.status(200).entity(distributor.toString()).build();
      }

谢谢。

【问题讨论】:

  • 奇怪的是,使用 Jersey 1.3 它对我来说非常有效,任何 1.4 或更高版本似乎都无法正常工作。使用 1.3 我在控制台中得到 distributors: {distributorId = 5, name = SA}
  • 嘿,即使使用 Jersey 1.3 也没有任何改变..
  • 如果我将JAXBElement&lt;Distributor&gt; element 改回Distributor distributor,它对我有用。否则我会得到:JSONMappingException: No suitable constructor found
  • 你能把你的项目发给我吗?

标签: java json rest jersey


【解决方案1】:

我所做的只是像这样更改返回类型:

@POST
@Path("/distpost")
@Produces(MediaType.APPLICATION_JSON)
public Response addDistributor(final Distributor distributor) {
    System.out.println(distributor);
    return Response.status(201).entity(distributor.toString()).build();
}

它会像这样处理 curl 测试:

curl -X POST -H 'Content-Type: application/json' -d '{"distributor": {"distributorId":5,"name":"SA"}}' <url>

【讨论】:

  • 在您发表评论后我已经尝试过,使用 Jersey 版本 1.3,但在加载我的 Apache 时抱怨一些 Servlet 不存在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多