Requestbody未映射到我在这里使用的对象。 PaymentRequest中的所有字段都为空。我看到注释和映射一切似乎都是正确的。
@RestController
@RequestMapping("/pay")
public class PaymentServiceAPIImpl {
@RequestMapping(value = "/request", method = RequestMethod.POST)
public Response submitPaymentRequest(@RequestBody PaymentRequest paymentRequest) {
System.out.println(paymentRequest.getClientId()); // here I am getting all the fields are null
return Response.ok().build();
}
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "payment_request", namespace = "http://www.abc-services.com/payment_request", propOrder = { "currencyCode", "clientId" })
public class PaymentRequest implements Serializable {
private static final long serialVersionUID = 1L;
@XmlElement(name = "currency_code")
protected String currencyCode;
@XmlElement(name = "client_id")
protected String clientId;
public String getCurrencyCode() {
return currencyCode;
}
public void setCurrencyCode(String value) {
this.currencyCode = value;
}
public String getClientId() {
return clientId;
}
public void setClientId(String value) {
this.clientId = value;
}
}
这是请求
curl -X POST \
http://localhost:8080/pay/request \
-H 'Cache-Control: no-cache' \
-H 'Content-Type: application/json' \
-H 'Postman-Token: fead689c-239-284bb2116ae2' \
-d '{
"payment_token": {
"client_id": "cyber",
"currency_code": "USD"
}
}'
将这样的付款请求输入控制器:
PaymentRequest {
clientId: null,
cardType: null,
cardIssuer: null
}
任何指针为何请求未映射到PaymentRequest?
答案 0 :(得分:1)
您的代码没有映射数据,因为JSON是一个具有名为payment_token
的单个属性的对象,并且您的参数类型PaymentRequest
没有该名称的属性。
将有效载荷更改为:
{
"client_id": "cyber",
"currency_code": "USD"
}
或更改参数类型以使用此类:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "payment_wrapper", namespace = "http://www.abc-services.com/payment_wrapper", propOrder = { "paymentToken" })
public class PaymentWrapper {
@XmlElement(name = "payment_token")
protected PaymentRequest paymentToken;
public PaymentRequest getPaymentToken() {
return paymentToken;
}
public void setPaymentToken(PaymentRequest value) {
this.paymentToken = value;
}
}
答案 1 :(得分:0)
您的请求使用JSON,但参数为XML。 发生了一些变化:
curl -X POST \
http://localhost:8080/pay/request \
-H 'Cache-Control: no-cache' \
-H 'Content-Type: application/json' \
-H 'Postman-Token: fead689c-239-284bb2116ae2' \
-d '{
"clientId": "cyber",
"currencyCode": "USD"
}'
public class PaymentRequest {
protected String currencyCode;
protected String clientId;
public String getCurrencyCode() {
return currencyCode;
}
public void setCurrencyCode(String value) {
this.currencyCode = value;
}
public String getClientId() {
return clientId;
}
public void setClientId(String value) {
this.clientId = value;
}
}