fastjson 布尔值处理

    xiaoxiao2021-03-25  101

    将json字符串转换成对象时,如果页面上输入的是0/1/Y/N等,但字段类型为boolean时,常规情况下会报错json类型转化错误.

    处理方法简单:利用对象的set方法的多态.多写一个set方法,参数为字符串

    //标准的set方法 public void setHasTax(boolean hasTax) { this.hasTax = hasTax; } /** * TRUE或者1或者Y,都等于true,否则为false * * @param hasTax */ public void setHasTax(String hasTax) { this.hasTax=BooleanUtils.toBoolTrue(hasTax); } public class BooleanUtils { /** * 除了TURE,Y和1,其他都为false * @param s * @return */ public static boolean toBoolFalse(String s){ if(s!=null&&(s.equals('Y')||s.equals("1")||s.toUpperCase().equals("TRUE"))){ return true; }else{ return false; } } /** * 除了FALSE,N,0,null,其他都为true * @param s * @return */ public static boolean toBoolTrue(String s){ if(s!=null){ if((s.equals('N')||s.equals("0")||s.toUpperCase().equals("FALSE"))){ return false; }else{ return true; } }else{ return false; } } /** * 将布尔值转换为Y或者N * @param b * @return */ public static String boolToStr(boolean b){ if(b){ return "Y"; }else{ return "N"; } } /** * 将布尔值转换为1或者0 * @param b * @return */ public static int boolToInt(boolean b){ if(b){ return 1; }else{ return 0; } } }
    转载请注明原文地址: https://ju.6miu.com/read-12341.html

    最新回复(0)