Android中新增布尔值始终转换为0的技术问题求助
问题排查与解决方案
核心原因分析
你的问题大概率出在接口返回字段与实体类字段的映射不匹配,以及基本类型boolean的默认值陷阱,具体如下:
1. 字段名映射错误
接口返回的字段是mon、tue、wen(注意是wen不是常规的wed)、thu等,但你的实体类中用的是monBool、tueBool、wenBool这类后缀带Bool的字段。如果使用Gson、Jackson等序列化框架,默认会严格匹配字段名,导致新增的7个字段无法正确反序列化,最终值为null(如果是包装类)或false(如果是基本类型),转成数据库的0。
2. 基本类型boolean的默认值陷阱
如果你的实体类中monBool等字段定义为基本类型boolean,当接口返回null时,序列化框架会自动将其转为false,最终转成0;而oncall字段一直正常,可能是因为接口从未返回过null,或者你的实体类中oncallBool的映射是正确的。
具体解决方案
步骤1:修正实体类字段映射
给实体类的新增字段添加序列化注解,明确对应接口返回的字段名,同时改用包装类Boolean避免null转默认false:
// 示例实体类字段定义 public class CustomerResultItem { // 其他已有字段 @SerializedName("oncall") public Boolean oncallBool; // 保持原有正确映射 // 新增字段的正确映射 @SerializedName("mon") public Boolean monBool; @SerializedName("tue") public Boolean tueBool; @SerializedName("wen") // 注意接口返回的是wen,不是wed public Boolean wenBool; @SerializedName("thu") public Boolean thuBool; @SerializedName("fri") public Boolean friBool; @SerializedName("sat") public Boolean satBool; @SerializedName("sun") public Boolean sunBool; // 其他字段... }
步骤2:完善null值处理逻辑
在转换为数据库存储的int值时,先判断字段是否为null,再处理布尔值:
// 优化后的字段转换代码 CustomerResultItem item = customerResult.d.results.get(i); int oncall = item.oncallBool != null && item.oncallBool ? 1 : 0; int mon = item.monBool != null && item.monBool ? 1 : 0; int tue = item.tueBool != null && item.tueBool ? 1 : 0; int wen = item.wenBool != null && item.wenBool ? 1 : 0; int thu = item.thuBool != null && item.thuBool ? 1 : 0; int fri = item.friBool != null && item.friBool ? 1 : 0; int sat = item.satBool != null && item.satBool ? 1 : 0; int sun = item.sunBool != null && item.sunBool ? 1 : 0; // 写入数据库 cusdatasource.createCustomer( Integer.parseInt(item.accountnumStr), oncall, OnCallDate, FromDate, ToDate, mon, tue, wen, thu, fri, sat, sun );
步骤3:调试验证
在转换前打印实体类字段值,确认反序列化是否成功:
Log.d("Debug", "monBool: " + item.monBool); Log.d("Debug", "tueBool: " + item.tueBool);
如果打印结果为null,说明字段映射仍有问题;如果是true/false,则检查转换逻辑是否正确。
内容的提问来源于stack exchange,提问作者Kim HJ
相关产品推荐
相关产品推荐

