常用方法
JSONObject、JSONArray继承抽象类JSON
- toJSONString
- parseObject
- toJSON
序列化
String jsonStr = JSON.toJSONString(student);
反序列化
// Javabean
Student student = JSON.parseObject(jsonStr1, Student.class);
// json对象
JSON json = JSON.parseObject(jsonStr1);
JSONObject jsonObject1 = JSON.parseObject(jsonStr1);
JSONObject jsonObject = JSONObject.parseObject(jsonStr1);
// jsonarray
String str = "[{\"name\":\"value\"},{\"name1\":\"value1\"},{\"name2\":\"value2\"}]";
JSONArray jsonArray = JSONArray.parseArray(str);
// 遍历
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONArray jsonArray1 = jsonArray.getJSONArray(i);
}
// hashmap
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("key1", "value1");
hashMap.put("key2", "value2");
hashMap.put("key3", "value3");
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(hashMap);
System.out.println(jsonObject.toString());
jsonObject.put("key4", "value4");
HashMap<String, String> hashMap2 = JSONObject.parseObject(jsonObject.toJSONString(), HashMap.class);
System.out.println(hashMap2.toString());
//list map
List<HashMap<String, String>> list = new ArrayList<>();
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("key1", "value1");
hashMap.put("key2", "value2");
hashMap.put("key3", "value3");
list.add(hashMap);
JSONArray jsonArray = (JSONArray) JSONArray.toJSON(list);
System.out.println(jsonArray.toJSONString());
List<HashMap<String, String>> list2 = JSONArray.parseObject(jsonArray.toJSONString(), List.class);
System.out.println(list2.toString());