Android中JSON的4种解析方式使用和对比

  /**

  * @Description: SDK org.json下自带的Json解析方式

  * @CreateDate: 2022/3/22 10:30 上午

  */

  public class OrgJsonUtil {

  /**

  * 生成Json

  */

  public static void createJson(Context context) {

  try {

  File file = new File(context.getFilesDir(), "orgjson.json");

  //实例化一个JSONObject

  JSONObject student = new JSONObject();

  //向对象中添加数据

  student.put("name", "Musk");

  student.put("sex", "男");

  student.put("age", 50);

  JSONObject course1 = new JSONObject();

  course1.put("name", "数学");

  course1.put("score", 98.2f);

  JSONObject course2 = new JSONObject();

  course2.put("name", "语文");

  course2.put("score", 99);

  //实例化一个JSONArray

  JSONArray courses = new JSONArray();

  courses.put(0, course1);

  courses.put(1, course2);

  student.put("courses", courses);

  //写数据

  FileOutputStream fos = new FileOutputStream(file);

  fos.write(student.toString().getBytes());

  fos.close();

  Log.d("TAG", "createJson: " + student);

  Toast.makeText(context, "Json创建成功", Toast.LENGTH_SHORT).show();

  } catch (Exception e) {

  e.printStackTrace();

  }

  }

  /**

  * 解析Json

  */

  public static void parseJson(Context context) {

  try {

  //读数据

  File file = new File(context.getFilesDir(), "orgjson.json");

  FileInputStream fis = new FileInputStream(file);

  InputStreamReader isr = new InputStreamReader(fis);

  BufferedReader br = new BufferedReader(isr);

  String line;

  StringBuffer sb = new StringBuffer();

  while (null != (line = br.readLine())) {

  sb.append(line);

  }

  fis.close();

  isr.close();

  br.close();

  Student student = new Student();

  JSONObject studentJsonObject = new JSONObject(sb.toString());

  //获取对象

  //使用optString在获取不到对应值的时候会返回空字符串"",而使用getString会异常

  String name = studentJsonObject.optString("name", "");

  String sex = studentJsonObject.optString("sex", "女");

  int age = studentJsonObject.optInt("age", 18);

  student.setName(name);

  student.setSex(sex);

  student.setAge(age);

  //获取数组

  List courses = new ArrayList<>();

  JSONArray coursesJsonArray = studentJsonObject.optJSONArray("courses");

  if (coursesJsonArray != null && coursesJsonArray.length() > 0) {

  for (int i = 0; i < coursesJsonArray.length(); i++) {

  JSONObject courseJsonObject = coursesJsonArray.optJSONObject(i);

  Course course = new Course();

  String courseName = courseJsonObject.optString("name", "学科");

  float score = (float) courseJsonObject.optDouble("score", 0);

  course.setName(courseName);

  course.setScore(score);

  courses.add(course);

  }

  }

  student.setCourses(courses);

  Log.d("TAG", "parseJson: " + student);

  Toast.makeText(context, "Json解析成功", Toast.LENGTH_SHORT).show();

  } catch (Exception e) {

  e.printStackTrace();

  }

  }

  }