前言:当数据进行json转换时,当属性值为null时,json解析就会中断,导致接下来的数据无法正确获取。原则上来讲服务器端发送的json字符串不允许存在属性值为空的情况,但是如果服务器端发送了null的属性值,客户端也必须要解决。

这里举个今天遇到json转换null值的实例,在下面提一下

代码

Bean

Hr

public class Hr {
    private Integer id;
    private String name;
    private String phone;
    private String telephone;
    private String address;
    private Boolean enabled;
    private String username;
    private String password;
    private String userface;
    private String remark;
    //防止null值,roles预先创建个List实例
    private List<Role> roles  = new ArrayList<>();
    //get、set省略

Role

public class Role {
    private Integer id;
    private String name;
    private String namezh;
    //get、set省略
}

Controller

@RestController
@RequestMapping("/system/hr")
public class HrController {
    @Autowired
    HrService hrService;
    @GetMapping("/")
    public List<Hr> getAllHrs(Integer id){
        return hrService.getAllHrs(id);
    }
}

Service

@Service
public class HrService implements UserDetailsService {
    @Resource
    HrMapper hrMapper;
    public List<Hr> getAllHrs(Integer id) {
        return hrMapper.getAllHrs(id);
    }
}

Mapper

java

public interface HrMapper {
    List<Hr> getAllHrs(Integer id);
}

xml

<resultMap id="BaseResultMap" type="com.lwy.vhr.bean.Hr">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="phone" jdbcType="CHAR" property="phone" />
    <result column="telephone" jdbcType="VARCHAR" property="telephone" />
    <result column="address" jdbcType="VARCHAR" property="address" />
    <result column="enabled" jdbcType="BIT" property="enabled" />
    <result column="username" jdbcType="VARCHAR" property="username" />
    <result column="password" jdbcType="VARCHAR" property="password" />
    <result column="userface" jdbcType="VARCHAR" property="userface" />
    <result column="remark" jdbcType="VARCHAR" property="remark" />
</resultMap>

<resultMap id="BaseResultMap2" type="com.lwy.vhr.bean.Hr" extends="BaseResultMap">
    <collection property="roles" ofType="com.lwy.vhr.bean.Role">
      <id column="rid" property="id" jdbcType="INTEGER"/>
      <result column="rname" property="name" jdbcType="VARCHAR"/>
      <result column="rnameZh" property="namezh" jdbcType="CHAR"/>
    </collection>
  </resultMap>
  <select id="getAllHrs" resultMap="BaseResultMap2">
    select h.*,r.`id` as rid,r.`name` as ranme ,r.`nameZh` as rnameZh from hr h,hr_role hrr,role r where h.`id`=hrr.`hrid` and hrr.`rid`=r.`id` and h.`id`!=#{id}
  </select>

数据库

测试

这里用Postman来进行测试

在这里出现了json转换失败的情况

处理

通过断点调试,从authorities这里打上断点进行debug调试

发现取值时出现了null值,然后回想起json对null值的处理时会停止执行,再搜寻着路径去查找原因。。。

总结:这里只是因为自己疏忽将原本有值的属性“变成”了null,在平时开发的时候也会有将原本为null值的属性通过json格式发送到前段做处理。这个时候只要把null值转换成" "空字符串就行了。(建议使用gson)

总结到这里,积累点点滴滴,一步一脚印,加油

posted on 2019-04-23 21:38  寒翼绵羊  阅读(12427)  评论(0编辑  收藏  举报