亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

@RequestBody 變量返回空屬性

@RequestBody 變量返回空屬性

斯蒂芬大帝 2021-11-24 18:35:08
我編寫了一個控制器,用于接收發布 json 的發布請求,但是當我嘗試訪問對象字段時,它返回 null。控制器的代碼如下package com.example;import com.example.Services.ZesaServices;import com.example.models.Zesa.ZesaRequest;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class MoneyResource {@RequestMapping("/services")public String getServices(){    return "We do everything";}@PostMapping(value="/zesa")public String payZesa(@RequestBody ZesaRequest newZesaRequest){    Logger log = LoggerFactory.getLogger(YomoneyResource.class);    log.info("Json Object parsed works eg: "+newZesaRequest.getMeterNumber());    return newZesaRequest.getMeterNumber().toString();  }}當我發送下面的請求時,我的代碼正在打印 null{   "AgentAccountDetails":"example:123",   "MeterNumber":"1110-52-8867",   "PaymentMethod":1,   "Amount":10.50,   "MobileNumber":"0123456789",   "TransactionType":1,   "PaymentAccountNumber":"0123456789",   "PaymentAccountDetails":"null"}當我運行它時,它返回一個空字符串。我不確定問題出在哪里,我查看了其他示例,他們遵循了類似的模式,我運行了他們的代碼,它按預期工作,但我的似乎沒有將 json 主體轉換為 Java 對象。
查看完整描述

2 回答

?
HUX布斯

TA貢獻1876條經驗 獲得超6個贊

您可以通過使用@JsonProperty字段上方的注釋來解決此問題,如下所示:


...

@JsonPropety(value = "Amount")

private Double amount;

...

或者,您可以按照評論中的建議,重命名您的屬性以小寫字母開頭(在 VM 中和傳入中json)@OrangeDog。


查看完整回答
反對 回復 2021-11-24
?
絕地無雙

TA貢獻1946條經驗 獲得超4個贊

您的類定義了一個名為的屬性meterNumber,但您的 JSON 對象卻說MeterNumber。


如果您必須MeterNumber在 JSON 中添加@JsonProperty注釋,則需要添加注釋。


以大寫字母開頭的字段名稱違反 Java 和 JSON 命名約定。


順便說一句,您可以通過使用Lombok來避免所有樣板:


@Data

public class ZesaRequest {

    @JsonProperty("Amount")

    private Double amount;


    @JsonProperty("MeterNumber")

    private String meterNumber;


    @JsonProperty("PaymentAccountNumber")

    private String paymentAccountNumber;


    @JsonProperty("PaymentAccountDetails")

    private String paymentAccountDetails;


    @JsonProperty("PaymentMethod")

    private int paymentMethod;


    @JsonProperty("MobileNumber")

    private String mobileNumber;


    @JsonProperty("AgentAccountDetails")

    private String agentAccountDetails;


    @JsonProperty("TransactionType")

    private int transactionType;

}

你也可能不想要"PaymentAccountDetails":"null". 它應該是"PaymentAccountDetails":null,或者完全省略。


查看完整回答
反對 回復 2021-11-24
  • 2 回答
  • 0 關注
  • 280 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號