我有一個包含多個無線電輸入和一個 textarea 輸入的表單,我使用來自 ReactJs 客戶端的 axios 發送。請求如下所示:
axios.post("/wellbeing/" params.wellbeingSurveyType, { formAnswersJson: formAnswers })
.then(res => {
// logic
})
.catch(err => {
// logic
})
“formAnswers”物件如下所示:

然后我收到來自 Spring 控制器的請求,如下所示:
@PostMapping("{wellbeingSurveyType}")
public WellbeingSurveySubmission submitSurvey(
@PathVariable WellbeingSurveyType wellbeingSurveyType,
@RequestBody String formAnswersJson) throws JsonProcessingException {
var result = new ObjectMapper().readValue(formAnswersJson, HashMap.class);
return new WellbeingSurveySubmission(); //ignore this
}
當我在結果物件上呼叫 'toString()' 方法時,它似乎正確列印出地圖值:

但是當我嘗試實際操作物件(被決議為 LinkedHashMap)時,我無法訪問鍵或值:

當我嘗試使用除錯工具打開物件時,它似乎將對自身的參考存盤為一個值:

我想要的結果只是一個表示 JSON 的 Map<String, String> 但我不確定為什么會發生這種行為。
任何有關如何以更好的方式執行此操作的幫助或提示將不勝感激,謝謝。
uj5u.com熱心網友回復:
好吧,我發現完成這項作業的最佳方法是解構 axios 發布請求中的 JSON 物件,如下所示:
axios.post("/wellbeing/" params.wellbeingSurveyType, { ...formAnswers })
.then(res => {
// logic
})
.catch(err => {
// logic
})
效果更好,就好像我只是傳遞了 formAnswers 物件,它不必要地包裝了物件,即包含單個鍵值對“formAnswers”的哈希圖。
盡管正如《冰雪奇緣》提到的,最好定義一個專用的表單物件并將其作為彈簧控制器中的引數。
uj5u.com熱心網友回復:
如果您將 JavaScript 物件作為第二個引數傳遞給axios.post()函式,Axios 會自動為您將物件序列化為 JSON。
因此,使用這行代碼:
axios.post("/wellbeing/" params.wellbeingSurveyType, { formAnswersJson: formAnswers })
您基本上是在將帶有鍵fromAnswersJson和值的物件發送fromAnswers到您的休息控制器,Spring 會像Map使用鍵fromAnswersJson和值一樣對其進行反序列化fromAnswers
要獲得您想要的,只需發送您的請求,如下所示:
axios.post("/wellbeing/" params.wellbeingSurveyType, formAnswers )
uj5u.com熱心網友回復:
從我在您的列印螢屏上看到的內容來看,Java 中從 String 到 Map 的轉換似乎并不順利。
就個人而言,我在處理請求時不會那樣作業。我創建了一個 dto 物件并在控制器中將其作為輸入。您有名稱是數字的變數這一事實使得這有點復雜,因為 java 不能接受它作為有效的變數名稱,但可能(沒有測驗它)可以通過使用 @JsonProperty 來克服。所以我的解決方案如下
@Getter
@Setter
public class MyRequestDto {
@JsonProperty("user-comment")
private String userComment;
@JsonProperty("0")
private String zero;
@JsonProperty("1")
private String one;
@JsonProperty("2")
private String two;
...
}
我添加了 lombok 的 getter 和 setter,當然如果你不使用 lombok,你也可以添加自己的。
然后替換控制器中的輸入
@PostMapping("{wellbeingSurveyType}")
public WellbeingSurveySubmission submitSurvey(
@PathVariable WellbeingSurveyType wellbeingSurveyType,
@RequestBody MyRequestDto request) throws JsonProcessingException {
request.getUserComment()
return new WellbeingSurveySubmission(); //ignore this
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/450849.html
