gpt4 book ai didi

java - JEE Restful 将 JSON 绑定(bind)到 JAVA

转载 作者:行者123 更新时间:2023-12-02 02:06:48 25 4
gpt4 key购买 nike

我们正在开发一个 Java EE 项目,需要公开一个使用 JSON 的 RESTFul Web 服务。不幸的是,我无法将 JSON 参数绑定(bind)到 Http-POST 请求中的 Java 对象。你能帮我吗?

服务类别:

@Path("claimserviceNew")
public class SlsiRestServicesNew {

@POST
@Consumes({"application/xml", "application/json"})
@Produces(MediaType.APPLICATION_JSON)
public String registerClaimWithPaymentNew( Mandant mandant, Vertrag vertrag){

return mandant.getCode() + " new ";
}

}

Mandant 类:

@XmlRootElement(name="mandant")
@XmlAccessorType(XmlAccessType.FIELD)
public class Mandant {


@XmlAttribute(required=true)
private String code;


public String getCode() {
return code;
}

public void setCode(String code) {
this.code = code;
}

}

Vertrag 类:

@XmlRootElement(name="vertrag")
@XmlAccessorType(XmlAccessType.FIELD)
public class Vertrag {

@XmlAttribute(required=true)
private String polizzenNummer;

public String getPolizzenNummer() {
return polizzenNummer;
}

public void setPolizzenNummer(String polizzenNummer) {
this.polizzenNummer = polizzenNummer;
}

}

我的 HTTP Post 请求中的两个 JSON 参数:

{   { 
"code": "SLV"
},

{
"polizzenNummer": "1234"
}

}

服务器异常:

Caused by: org.codehaus.jackson.JsonParseException: Unexpected character ('{' (code 123)): was expecting double-quote to start field name
at [Source: org.apache.catalina.connector.CoyoteInputStream@cce46; line: 1, column: 6]
at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:1433) [jackson-core-asl-1.9.9-redhat-2.jar:1.9.9-redhat-2]

最佳答案

您的 REST 方法只能通过 Json 绑定(bind)接收一个对象。在这种情况下,您可能希望创建一个封装两者的对象:

public class MyInput {
private Vertrag vertrag;
private Mandant mandant;
// .. getters and setters
}

然后您会在 REST 方法中收到此消息:

@POST
@Consumes({"application/xml", "application/json"})
@Produces(MediaType.APPLICATION_JSON)
public String registerClaimWithPaymentNew(MyInput input){

return input.getMandant().getCode() + " new ";
}

关于java - JEE Restful 将 JSON 绑定(bind)到 JAVA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50639100/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com