1.字符串与对象转换

1.1 字符串转对象

  1. JSONObject jsonObject = JSONObject.parseObject(str);//转json对象
  2. Student student = JSONObject.parseObject(str, Student.class);//转java对象

1.2 对象转字符串

String str1 = JSONObject.toJSONString(javaObject);//java对象转换成string
String str2 = JSONObject.toJSONString(jsonObject);//json对象转换成string

1.3 对象转对象

JSONObject jsonObject = (JSONObject) JSONObject.toJSON(javaObject);
Student javaObject = JSONObject.toJavaObject(jsonObject, Student.class);

2.获取jsonObject属性值

jsonObject.getString("name");
jsonObject.getInteger("age");
jsonObject.getObject("school", School.class);

3.JsonArray遍历

JSONObject jsonObject = JSONObject.parseObject(json);
JSONArray studentArrayList = jsonObject.getJSONArray("studentArrayList");
for (Object o : studentArrayList) {//遍历的对象只能使用Object对象接收
    //o实质是一个jsonObject对象
    Student o1 = JSONObject.toJavaObject((JSONObject)o, Student.class);
    System.out.println(o1.getName());
    System.out.println(o1.getSchool());
    System.out.println("==============");
}

遍历的JSONArray的对象只能使用Object对象接收,这是因为JSONArray是一个List集合,其泛型是Object
Snipaste_2020-08-12_20-21-23.png

4.JSONObject的见解

  • JSONObject其实就是一个Map的子类