序列化一个对象成为JSON字符串
User user = new User();
user.setName("小白");
user.setAge(12);
user.setEmail("234@qq.com");
String formarStr = JSON.toJSONString(user);
KLog.d("输出信息--", formarStr);
输出信息
{"age":12,"email":"234@qq.com","name":"小白"}
反序列化一个JSON字符串成为一个对象
String jsonString = "{\"name\":\"小黑\",\"age\":20,\"email\":\"333@qq.com\"}";
User user1 = JSON.parseObject(jsonString,User.class);
KLog.d("输出信息--", user1.toString());
输出信息
User{name='小黑', age=20, email='333@qq.com'}
数组序列化成为JSON字符串
List<User> users = new ArrayList<>();
users.add(user);
users.add(user1);
String userStr = JSON.toJSONString(users);
KLog.d("输出信息-userStr-", userStr);
输出信息
[{"age":12,"email":"234@qq.com","name":"小白"},{"age":20,"email":"333@qq.com","name":"小黑"}]
JSON字符串反序列化为数组
List<User> user2 = JSON.parseArray(userStr,User.class);
KLog.d("输出信息-user2.size()-", user2.size());
输出信息
2
序列化Map成为JSON字符串
Map<String,Object> dataMap = new HashMap<>();
dataMap.put("tag", "data");
dataMap.put("hospitalName", "我是医院名字");
dataMap.put("name", "欧阳夏凡");
dataMap.put("gender", "女");
dataMap.put("age", "28");
dataMap.put("code", "420502042");
dataMap.put("examineDoc", "杨林");
dataMap.put("examineDate", "2016-05-10");
dataMap.put("verifyDoc", "王菲");
KLog.d("MapToJson-", JSON.toJSONString(dataMap));
输出信息
{"age":"28","code":"420502042","examineDate":"2016-05-10","examineDoc":"杨林","gender":"女","hospitalName":"我是医院名字","name":"欧阳夏凡","tag":"data","verifyDoc":"王菲"}
反序列化JSON字符串到Map
Map<String,Object> dataMap = new HashMap<>();
dataMap.put("tag", "data");
dataMap.put("hospitalName", "我是医院名字");
dataMap.put("name", "欧阳夏凡");
dataMap.put("gender", "女");
dataMap.put("age", "28");
dataMap.put("code", "420502042");
dataMap.put("examineDoc", "杨林");
dataMap.put("examineDate", "2016-05-10");
dataMap.put("verifyDoc", "王菲");
KLog.d("MapToJson-", JSON.toJSONString(dataMap));
Map<String,Object> maps = JSON.parseObject(JSON.toJSONString(dataMap),Map.class);
KLog.d("JsonToMap-",maps.toString());
方法
Map<String,Object> maps = JSON.parseObject(JSON.toJSONString(dataMap),Map.class);
输出结果
{age=28, tag=data, examineDate=2016-05-10, verifyDoc=王菲, name=欧阳夏凡, gender=女, examineDoc=杨林, hospitalName=我是医院名字, code=420502042}
如果只想解析某个属性
User user = new User();
user.setName("小白");
user.setAge(12);
user.setEmail("234@qq.com");
SimplePropertyPreFilter filter = new SimplePropertyPreFilter(User.class, "name");
String formarStr = JSON.toJSONString(user,filter);
KLog.d("输出信息--", formarStr);
输出结果
{"name":"小白"}
网友评论