我制作了一个 Spring Boot 2 REST 应用程序。我正在将 REST 与 Angular 一起使用。我在枚举方面遇到问题。
典型的枚举服务器端是:
public enum EngineType {
DIESEL, METHANE, ELECTRIC;
@Nullable
public static EngineType valueOfNullable(String value) {
try {
return valueOf(value);
} catch (Exception e) {
return 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());
}
}
但我应该将此注释 @JsonDeserialize(using = EngineTypeDeserializer.class)
放在我的 beans 中的所有 EngineType
字段中。
我一直在寻找更好的方法来解决这个问题。你有什么建议吗?
最佳答案
您可以通过编程方式注册自定义序列化程序。
在您的@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);
}
关于java - 在 Spring Boot 应用程序的 REST 调用中接受 Enum 的空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50422943/