简体   繁体   English

在使用SpringBoot绑定之前,有没有办法将JSON值大写?

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

I am working on a SpringBoot REST service. 我正在使用SpringBoot REST服务。 The REST service works when the UI sends the right JSON values (formatted). 当UI发送正确的JSON值(格式化)时,REST服务即可工作。

Sometimes the UI team will forget to upper case a property value and cause an exception. 有时,UI团队会忘记大写一个属性值并导致异常。 I want to make the REST service handle such cases. 我想让REST服务处理这种情况。

JSON property is being POSTed as JSON属性被发布为

"category":"patient"

It is supposed to be POSTed with uppercase. 应该以大写形式发布。

"category":"PATIENT"

The Java object property category is a ENUM Java对象属性类别是ENUM

public enum StaffCategory {
    PATIENT, EQUIPMENT
}

The ui model object 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;

This is the error I get 这是我得到的错误

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

Although UI team should stick to backend API specs, still you can use ObjectMapper configuration to overcome this specific scenario: 尽管UI团队应该坚持使用后端API规范,但是您仍然可以使用ObjectMapper配置来克服此特定情况:

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

You dont need to convert it to uppercase because it lowers readability and also avoids maintainability.You only need to change your Enum definition as: 您不需要将其转换为大写字母,因为它会降低可读性并避免可维护性。您只需将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; }
}

This way it get easily deserialized with no breaking your code or facing any problems. 这样,它很容易反序列化而不会破坏您的代码或面临任何问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM