目录
一、json基础
1.什么是json
2.json数据表示
- 数据结构
object
array
- 基本类型
二、java中的json
1.创建json对象
JSONObject object = new JSONObject();
object.put("name","李四");
注意:相同的key会覆盖
2.通过map创建json对象
Map<String,Object> map=new HashMap<>();
map.put("name","张三");
JSONObject object = new JSONObject(map);
3.使用java bean创建json对象
User user = new User();
user.setName("张三");
JSONObject object = new JSONObject(user);
4.通过json 字符串创建json对象
JSONObject object = new JSONObject(str);
5.json与其他类型的转换
(1)json字符串 对象
-
json字符串转对象
jsonString = "{\"name\":\"张三\",\"age\":18}";
object = JSONObject.parseObject(jsonString);
user = JSONObject.toJavaObject(object,User.class);
- 对象转json字符串
jsonString = JSONObject.toJSONString(user);
(2)json字符串 map
-
json字符串转map
jsonString = "{\"name\":\"张三\",\"age\":18}";
map = (Map<String, Object>) JSONObject.parse(jsonString);
(3)json字符串转对象list
jsonString = "[{\"name\":\"张三\",\"age\":18},{\"name\":\"里斯\",\"age\":18}]";
array = JSONObject.parseArray(jsonString);
list = JSONObject.toJavaObject(array,List.class);
(4)json字符串 json对象
- json字符串转json对象
jsonString = "{\"name\":\"张三\"}";
object = JSONObject.parseObject(jsonString);
- json对象转json字符串
object = new JSONObject();
object.put("name","李四");
jsonString = JSONObject.toJSONString(object);
(5)json字符串 json数组
- json字符串转json数组
jsonString = "[{\"name\":\"张三\"},{\"age\":18}]";
array = JSONArray.parseArray(jsonString);
- json数组转json字符串
jsonString = JSONArray.toJSONString(array);
(6)map json对象
- map转json对象
map.put("name","张三");
object = new JSONObject(map);
- json对象转map
map = object.getInnerMap();
(7)对象转json对象
- 对象转json对象
object = JSONObject.fromObject(user);
- json对象转对象
user = JSONObject.toJavaObject(object,User.class);
https://www.cnblogs.com/heqiyoujing/p/9840424.html