You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Jackson ObjectMapper以支持True/False替代true/false?

Jackson如何自动处理首字母大写的布尔值(True/False)?

问题背景

我遇到了JSON格式不规范的问题:布尔值使用了"key":True而非JSON标准的"key":true,解析时抛出如下错误:

com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'True': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')

目前可以通过解析前对JSON字符串执行replace("True", "true")临时解决,但希望通过Jackson的配置自动处理这种情况,是否可行?

当前使用的Jackson代码:

private static final ObjectMapper jsonMapper;
JsonFactory f = JsonFactory.builder()
    .enable(JsonReadFeature.ALLOW_LEADING_ZEROS_FOR_NUMBERS)
    .enable(JsonReadFeature.ALLOW_SINGLE_QUOTES)
    .build();

jsonMapper = JsonMapper.builder(f).build();

JsonNode res = jsonMapper.readTree(content);

不规范的JSON示例:

{
  ...,
  "key" : True,
  ...
}

解决方案

Jackson支持通过配置自动识别大小写不规范的布尔值,有两种配置方式可选:

方式1:仅针对布尔值启用大小写不敏感解析

如果只需要处理布尔值的大小写问题,不影响其他类型或字段名的解析,启用DeserializationFeature.ACCEPT_CASE_INSENSITIVE_BOOLEANS即可:

JsonFactory f = JsonFactory.builder()
    .enable(JsonReadFeature.ALLOW_LEADING_ZEROS_FOR_NUMBERS)
    .enable(JsonReadFeature.ALLOW_SINGLE_QUOTES)
    .build();

jsonMapper = JsonMapper.builder(f)
    .enable(DeserializationFeature.ACCEPT_CASE_INSENSITIVE_BOOLEANS) // 专门适配布尔值大小写
    .build();

方式2:全局启用值的大小写不敏感解析

如果需要同时支持其他值类型的大小写不敏感解析(比如数字的大小写形式,场景较少),可以启用MapperFeature.ACCEPT_CASE_INSENSITIVE_VALUES:

JsonFactory f = JsonFactory.builder()
    .enable(JsonReadFeature.ALLOW_LEADING_ZEROS_FOR_NUMBERS)
    .enable(JsonReadFeature.ALLOW_SINGLE_QUOTES)
    .build();

jsonMapper = JsonMapper.builder(f)
    .enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_VALUES) // 全局值大小写不敏感
    .build();

两种配置都能让Jackson自动识别True/TRUE/False/FALSE这些非标准布尔值,无需手动修改JSON字符串。

内容的提问来源于stack exchange,提问作者Vincent Laval

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 20:15:35