簡體   English   中英

在使用SpringBoot綁定之前,有沒有辦法將JSON值大寫?

[英]Is there a way to upper case a JSON value before binding it - using SpringBoot?

我正在使用SpringBoot REST服務。 當UI發送正確的JSON值(格式化)時,REST服務即可工作。

有時,UI團隊會忘記大寫一個屬性值並導致異常。 我想讓REST服務處理這種情況。

JSON屬性被發布為

"category":"patient"

應該以大寫形式發布。

"category":"PATIENT"

Java對象屬性類別是ENUM

public enum StaffCategory {
    PATIENT, EQUIPMENT
}

ui模型對象

@JsonProperty("category")
private StaffCategory category;

@JsonProperty("category")
public StaffCategory getCategory() {
    return category;
}

@JsonProperty("category")
public void setCategory(StaffCategory category) {
    this.category = category;
}

@JsonProperty("category")
private StaffCategory category;

這是我得到的錯誤

    Can not deserialize value of type model.constants.StaffCategory 
from String "patient": value not one of declared Enum instance names: [PATIENT, EQUIPMENT]

盡管UI團隊應該堅持使用后端API規范,但是您仍然可以使用ObjectMapper配置來克服此特定情況:

@Bean
public ObjectMapper objectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS, true);
    return mapper;
}

您不需要將其轉換為大寫字母,因為它會降低可讀性並避免可維護性。您只需將Enum定義更改為:

public enum StaffCategory {
    PATIENT("patient"), EQUIPMENT("equipment");

    private String value;
    private StaffCategory(String value) { this.value = value; }

    @JsonValue
    public String getValue() { return this.value; }
}

這樣,它很容易反序列化而不會破壞您的代碼或面臨任何問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM