[英]Spring Contracts: how to send a Collection of Strings as a RequestBody
[英]How to send a string with quotemarks in the RequestBody?
我有以下 API 方法:
@PatchMapping("/{id}")
public ResponseEntity<?> partialProjectUpdate(@PathVariable long id, @RequestBody EntryStatus status) throws DailyEntryNotFoundException {
return dailyEntryService.partialDailyEntryUpdate(id, status);
}
EntryStatus
是一個枚舉:
public enum EntryStatus {
OPEN,
PROGRESS,
CHECKED,
BOOKED,
UNAVAILABLE;
private static Map<String, EntryStatus> namesMap = new HashMap<String, EntryStatus>(3);
static {
namesMap.put("OPEN", OPEN);
namesMap.put("PROGRESS", PROGRESS);
namesMap.put("CHECKED", CHECKED);
namesMap.put("BOOKED", BOOKED);
namesMap.put("UNAVAILABLE", UNAVAILABLE);
}
@JsonCreator
public static EntryStatus forValue(String value) {
return namesMap.get(value);
}
@JsonValue
public String toValue() {
for (Map.Entry<String, EntryStatus> entry : namesMap.entrySet()) {
if (entry.getValue() == this)
return entry.getKey();
}
return null; // or fail
}
}
我像這樣調用 typescript 中的方法:
partialUpdateDailyEntry(dailyEntry: DailyEntry, status): Observable<any> {
const statusName: string = status.name;
return this.http.patch(BASE_URL + dailyEntry.id, statusName, this.authService.setHeaders('application/json'))
.pipe(
catchError(this.handleService.error)
);
}
statusName
是一個字符串,但問題是它通過 JSON 發送時不帶引號。 RequestBody
是例如OPEN
而不是"OPEN"
,這給了我以下錯誤:
JSON parse error: Unrecognized token 'OPEN': was expecting ('true', 'false' or 'null').
如前所述,這是由於字符串是在沒有引號的情況下發送的。
我可以通過手動將引號添加到statusName
來解決這個問題,如下所示:
const statusName: string = '"' + status.name + '"';
但這不可能是正確的解決方案,有更好的方法嗎?
嘗試
@JsonFormat(shape = JsonFormat.Shape.STRING)
public enum EntryStatus{
OPEN,
PROGRESS,
CHECKED,
BOOKED,
UNAVAILABLE;
}
您正在添加要發送JSON
的 header ,但"OPEN"
不是有效的 JSON 值。
您應該更改標題:
this.authService.setHeaders('text/plain')
或更改發送方式:
this.http.patch(BASE_URL + dailyEntry.id, { status: statusName});
並更改您的 java 后端以處理接收 object 並讀取狀態
或者在發送之前對其進行字符串化:
const statusName: string = JSON.stringify(status.name);
也許你可以把
namesMap.put("OPEN", OPEN);
作為
namesMap.put("\"OPEN\"", OPEN);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.