0

我将 JAX-RS (CXF) 与 JaxB 和 Jackson 一起使用来提供 REST-API。不幸的是,找到的结果都没有帮助我解决以下(简单)问题:

我实现了以下方法:

@POST
@Path(ApiStatics.ARMY_CREATE_ARMY)
public com.empires.web.dto.Army createArmy(@FormParam("locationid") long locationId, @FormParam("name") String name, @FormParam("troops") ArmyTroops troops) {

这是我的模型类:

@XmlRootElement
@XmlSeeAlso(ArmyTroop.class)
public class ArmyTroops {

    public ArmyTroops() {
    }

    public ArmyTroops(List<ArmyTroop> troops) {
        this.troops = troops;
    }

    @XmlElement(name = "troops")
    private List<ArmyTroop> troops = new ArrayList<ArmyTroop>();

    public List<ArmyTroop> getTroops() {
        return troops;
    }

    public void setTroops(List<ArmyTroop> troops) {
        this.troops = troops;
    }
}

陆军部队

@XmlRootElement(name = "troops")
public class ArmyTroop {

    @XmlElement
    private long troopId;

    @XmlElement
    private String amount;

    public long getTroopId() {
        return troopId;
    }

    public void setTroopId(long troopId) {
        this.troopId = troopId;
    }

    public String getAmount() {
        return amount;
    }  

    public void setAmount(String amount) {
        this.amount = amount;
    }
}

我发送的 json 如下所示:

locationid  1
name    asdasd
troops  {"troops":[{"troopId":4,"amount":"5"},{"troopId":6,"amount":"5"}]}

不幸的是,对象没有被转换。相反,我收到此错误:

InjectionUtils #reportServerError - Parameter Class com.empires.web.dto.in.ArmyTroops has no constructor with single String parameter, static valueOf(String) or fromString(String) methods

如果我为构造函数提供一个字符串参数,我会得到传递给“部队”的整个 json 字符串,如上所述。

任何想法为什么 JaxB 在这一点上不起作用?

4

1 回答 1

0

您正在使用 @Form 注释传递所有参数。但是http消息的Form部分必须是xml数据结构。您的 3 个参数没有主要的 xml 数据结构,因此它不起作用。简而言之,表单参数作为正文发送。cxf 使用 MultivaluedMap 发送参数(cxf 有一个用于此结构的 xml 模型)。如您所见,它不适合无法简单序列化的参数。

在这里,我的解决方案是删除 @FormParam 以避免该问题:

1) 使用@PathParam @CookieParam 发送您的前两个参数,而“无标签”(正文)仅用于军队组合。

2)定义一个接受所有参数的超级对象,可以序列化为xml数据结构,并使用“无标签”(正文)发送。

3)使用肥皂,使用 cxf 很容易同时获得 Rest 和 Soap。

于 2013-07-06T08:53:31.870 回答