【发布时间】: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<Distributor> element改回Distributor distributor,它对我有用。否则我会得到:JSONMappingException: No suitable constructor found -
你能把你的项目发给我吗?