簡體   English   中英

在Spring Boot應用程序的REST調用中為Enum接受空字符串

[英]Accept empty String for Enum in REST calls in Spring Boot application

我制作了一個Spring Boot 2 REST應用程序。 我正在使用Angular使用REST。 我有一個枚舉問題。

典型的枚舉服務器端是:

public enum EngineType {
    DIESEL, METHANE, ELECTRIC;

    @Nullable
    public static EngineType valueOfNullable(String value) {
        try {
            return valueOf(value);
        } catch (Exception e) {
            return null;
        }
    }
}

一些實體將這些枚舉用作字段,當然它們可以為null。 不幸的是,當客戶端對發送枚舉“”(空字符串)的實體進行POST(因為它可以為null)時,我在服務器端遇到了錯誤:

org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `server.model.enums.EngineType` from String "": value not one of declared Enum instance names: [DIESEL, METHANE, ELECTRIC]; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `server.model.enums.EngineType` from String "": value not one of declared Enum instance names: [DIESEL, METHANE, ELECTRIC]
 at [Source: (PushbackInputStream); line: 1, column: 153] (through reference chain: server.model.tickets.Ticket["engineType2"])

我了解消息的含義,因此可以解決創建自定義解串器的問題,如下所示:

@Component
public class EngineTypeDeserializer extends JsonDeserializer<EngineType> {

    @Override
    public EngineType deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        JsonNode node = jp.getCodec().readTree(jp);
        return EngineType.valueOfNullable(node.asText());
    }

}

但我應該在我的bean的所有EngineType字段中都@JsonDeserialize(using = EngineTypeDeserializer.class)此注釋@JsonDeserialize(using = EngineTypeDeserializer.class)

我一直在尋找解決此問題的更好方法。 你有什么建議嗎?

您可以以編程方式注冊自定義序列化程序。

在您的@Configuration類中:

@Bean
@Primary // Use this to shadow other objectmappers, if anny
public ObjectMapper objectMapper(){
    ObjectMapper objMapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.addDeserializer(EngineType.class, new EngineTypeDeserializer());
    objMapper.registerModule(module);
}

暫無
暫無

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

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