一、Gson
序列化
private String testToJson(){
Map<String,Object> map = new HashMap<>();
map.put("name", "张三");
map.put("age", 18);
map.put("email", "[email protected]");
map.put("IDCard", null);
map.put("tel", "");
return gson.toJson(map);
}
得到的结果
{"name":"张三","tel":"","age":18,"email":"[email protected]"}
从得到的结果来看,当字段值为null时,Gson默认会忽略该字段,使用时需要注意。
反序列化
private Map<String,Object> testFromJson(){
/*两种写法都是可以的,第二种写法如果值为空,必须写为'',否则会抛异常*/
String json = "{\"name\":\"张三\",\"tel\":\"\",\"age\":18,\"email\":\"[email protected]\"}";
//String json = "{name=张三, tel='', age=18.0, [email protected]}";
return gson.fromJson(json, HashMap.class);
}