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

Android中Jackson XML反序列化boolean/int类型失败问题求助

解决方案:全局配置Jackson自动转换字符串到boolean/int

方法1:通过CoercionConfig全局开启字符串到数值/布尔的强制转换

你之前尝试的CoercionConfig无效,大概率是配置方式不正确。正确的全局配置方式如下,只需修改XmlMapper的初始化逻辑,就能让所有boolean/int字段自动处理字符串形式的"1"/"0"或数字字符串:

this.mXmlMapper = new XmlMapper();
// 保留你原有的配置
this.mXmlMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
this.mXmlMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
this.mXmlMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
this.mXmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);

// 全局配置:允许字符串"1"/"0"转为boolean类型
this.mXmlMapper.coercionConfigFor(LogicalType.Boolean)
        .setCoercion(CoercionInputShape.String, CoercionAction.AsBoolean);

// 全局配置:允许数字字符串转为int类型
this.mXmlMapper.coercionConfigFor(LogicalType.Integer)
        .setCoercion(CoercionInputShape.String, CoercionAction.AsInteger);

方法2:注册自定义模块(更灵活,支持扩展)

如果需要更定制化的转换逻辑(比如额外支持"yes"/"no"转布尔值),可以注册一个全局生效的自定义模块:

public class XmlStringCoercionModule extends SimpleModule {
    public XmlStringCoercionModule() {
        // 处理Boolean类型的字符串转换
        addDeserializer(Boolean.class, new JsonDeserializer<Boolean>() {
            @Override
            public Boolean deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
                String value = p.getText().trim();
                return "1".equals(value) || "true".equalsIgnoreCase(value);
            }
        });
        // 处理Integer类型的字符串转换
        addDeserializer(Integer.class, new JsonDeserializer<Integer>() {
            @Override
            public Integer deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
                return Integer.parseInt(p.getText().trim());
            }
        });
    }
}

然后在XmlMapper初始化时注册该模块:

this.mXmlMapper.registerModule(new XmlStringCoercionModule());

补充:之前方案无效的原因

  • @JsonFormat(shape = JsonFormat.Shape.STRING):该注解仅作用于序列化(把数值转成字符串输出),无法处理反序列化时的字符串转数值场景,因此对你的问题无效。
  • 带@JsonCreator的构造方法:确实能解决单类的转换问题,但需要每个类重复编写,不符合简洁性需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 02:37:37