前言:當數據進行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)