@JsonSubTypes 不区分大小写

问题描述 投票:0回答:2
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes({
        @Type(value = CertificateAuth.class, name = "certificate"),
        @Type(value = UsernamePasswordCredentials.class, name = "usernamepassword"),
        @Type(value = APIKeyCredentials.class, name = "apikey")
})

在请求json中,对于类型值如何使其不区分大小写?

例如:类型应采用“usernamepassword”(或)“userNamePassword”(或)USERNAMEPASSWORD。

请注意:Json 到 POJO 的映射会像 RestController 一样自动发生

请帮助我

java json spring-mvc jackson jackson-databind
2个回答
0
投票

如果您需要将

type
值转换为小写字符串,您可以将 json 文件转换为
JsonNode
树,然后使用
ObjectMapper#treeToValue
方法将其转换为 pojo:

JsonNode root = mapper.readTree(json);
((ObjectNode) root).put("type", root.get("type").asText().toLowerCase());
YourPojo yourPojo = mapper.treeToValue(root, YourPojo.class);

0
投票

我认为有更好的解决方案。尝试像这样配置你的映射器:

ObjectMapper mapper = JsonMapper.builder().enable(
        MapperFeature.ACCEPT_CASE_INSENSITIVE_VALUES,
        MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS) //in case you use enum
        .build();
© www.soinside.com 2019 - 2024. All rights reserved.