Jackson数组转POJO仅在Android端失效问题求助
解决Android端Jackson数组转POJO反序列化失败的问题
看起来你遇到的是Jackson在Android端处理数组结构转POJO时的字段顺序匹配问题。JVM环境下Jackson默认可能按字段声明顺序匹配数组元素,但Android端的Jackson(尤其是和Android SDK集成或通过Retrofit等框架使用时)可能采用了不同的字段排序策略(比如字母序),导致空的@JsonPropertyOrder注解没有起到预期作用,进而把字符串值错误映射到了Long类型字段上。
下面是具体的修复方案:
方案1:显式指定@JsonPropertyOrder的字段顺序
因为JSON是数组结构,Jackson需要严格按照数组元素的顺序映射到POJO字段。你需要把@JsonPropertyOrder的参数设置为和JSON数组完全对应的字段顺序,确保跨环境的一致性:
@JsonFormat(shape = JsonFormat.Shape.ARRAY) @JsonPropertyOrder({ "openTime", "open", "high", "low", "close", "volume", "closeTime", "quoteAssetVolume", "numberOfTrades", "takerBuyBaseAssetVolume", "takerBuyQuoteAssetVolume" }) @JsonIgnoreProperties(ignoreUnknown = true) public class Lilin { public Long openTime; public String open; public String high; public String low; public String close; public String volume; public Long closeTime; public String quoteAssetVolume; public Long numberOfTrades; public String takerBuyBaseAssetVolume; public String takerBuyQuoteAssetVolume; }
注意顺序必须和JSON数组元素一一对应:数组第1个元素对应openTime,第2个对应open,以此类推,最后一个多余的元素会被@JsonIgnoreProperties忽略。
方案2:使用@JsonProperty指定数组索引
另一种更直观的方式是给每个字段添加@JsonProperty注解,明确指定对应的数组索引(从0开始),彻底避免顺序依赖问题:
@JsonFormat(shape = JsonFormat.Shape.ARRAY) @JsonIgnoreProperties(ignoreUnknown = true) public class Lilin { @JsonProperty(index = 0) public Long openTime; @JsonProperty(index = 1) public String open; @JsonProperty(index = 2) public String high; @JsonProperty(index = 3) public String low; @JsonProperty(index = 4) public String close; @JsonProperty(index = 5) public String volume; @JsonProperty(index = 6) public Long closeTime; @JsonProperty(index = 7) public String quoteAssetVolume; @JsonProperty(index = 8) public Long numberOfTrades; @JsonProperty(index = 9) public String takerBuyBaseAssetVolume; @JsonProperty(index = 10) public String takerBuyQuoteAssetVolume; }
这种方式每个字段都明确绑定数组位置,后续调整字段顺序也不会影响反序列化逻辑。
额外检查:统一Jackson版本
建议确认JVM和Android端使用的Jackson版本一致,不同版本的注解处理逻辑可能存在差异。比如在Android的build.gradle中指定明确版本:
implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.2' implementation 'com.fasterxml.jackson.core:jackson-core:2.15.2' implementation 'com.fasterxml.jackson.core:jackson-annotations:2.15.2'
修改后重新在Android端测试,应该就能正常完成反序列化了。
内容的提问来源于stack exchange,提问作者Putra Ardiansyah
相关产品推荐
相关产品推荐

