转换:JSONObject ---> XXXX
JSONObject ---> 自定义类对象
Student student = JSONObject.parseObject(jsonString,Student.class);JSONObject ---> Map集合
Map map = JSONObject.parseObject(jsonString, Map.class);JSONObject ---> JSONArray
方式一 JSONArray jsonArray = jsonObject.getJSONArray("键名");
方式二 JSONArray jsonArray = JSONArray.parseArray(jsonObject.getString("键名"));
转换:XXXX ---> JSONObject
Java对象转化成JSON字符串
Student student = new Student();
student.setId("1");
student.setName("aoteman");
String studentJson = JSON.toJSONString(student);字符串 ----> JSONObject:
JSONObject jsonObject = JSONObjcet.parseObject(jsonStr);JSONArray ----> JSONObject
JSONObject jsonObject= (JSONObject) jsonArray.get(index值);
取值:
- 获取JSONArray JSONArray jsonArray = jsonObject.getJSONArray("键名");
- 获取JSONObjet JSONObject jsonObject = jsonArray.getJSONObject(索引值) ;
- JSONObject jsonObject= (JSONObject) jsonArray.get(index值);
- 对象值 String Str = jsonObject.getString("键名");
- String Str = jsonObject.get(索引值);
- 获取列表/数组 List list = JSON.parseArray(jsonStr)x;
- String[] Arr = (jsonStr.substring(1, jsonStr.length() - 1)).split(",");
设值:
- jsonObject.put("键名", 值);
- jsonArray.add(jsonObject);
put,accumulate,element的方法区别:
- 1. jsonObject.put(key,value) : 原value有则替换,无则新增
- 2. jsonObject.accumulate(key,value) : value有则累积,无则新增
- 3. jsonObject.element(key,value) : 原key存在,新value为空,则原key移除;新value不为空则调用accmulate方法