String → JSONObject

  1. public static JSONObject parseObject(String text)
  2. // eg:
  3. JSONObject jsonObject = JSON.parseObject(result);

String → Java对象

  1. public static T parseObject(String text, Class clazz)
  2. // eg:
  3. BaseVo question = JSON.parseObject(result, BaseVo.class);

复合型结构:

  1. public static <T> T parseObject(String text, TypeReference<T> type, Feature... features)
  2. // String → map<String,Object> 如:{"code":"1","question":{"queId":"123"}}
  3. HashMap<String,QuestionBaseVo> map =JSON.parseObject(result, new TypeReference<HashMap<String,QuestionBaseVo>>(){});
  4. // String → List<List<Object>> 如:[[{"queId":"123"}]]
  5. List<List<BaseVo>> list = JSON.parseObject(result, new TypeReference<List<List<BaseVo>>>(){});

JSONObject → json字符串

  1. String jsonString = jsonObject.toJSONString();

json 字符串 → 数组类型到 JSONArray 的转换

  1. JSONArray jsonArray = JSONArray.parseArray(JSON_ARRAY_STR);

JSONArray → json 字符串

  1. //已知JSONArray,目标要转换为json字符串
  2. JSONArray jsonArray = JSONArray.parseArray(JSON_ARRAY_STR);
  3. String jsonString = JSONArray.toJSONString(jsonArray);

JavaBean → json字符串

  1. Student student = new Student("lily", 12);
  2. String jsonString = JSONObject.toJSONString(student);

json 字符串 → JavaBean_List 的转换

  1. // 第一种方式,使用TypeReference类,由于其构造方法使用protected进行修饰,故创建其子类
  2. List studentList = JSONArray.parseObject(JSON_ARRAY_STR, new TypeReference<ArrayList>() {});
  3. System.out.println("studentList: " + studentList);
  4. // 第二种方式,使用Gson的思想
  5. List studentList1 = JSONArray.parseArray(JSON_ARRAY_STR, Student.class);
  6. System.out.println("studentList1: " + studentList1);

List → json字符串

  1. List students = new ArrayList();
  2. String jsonString = JSONArray.toJSONString(students);

复杂 json 格式字符串 → javaBean

  1. //第一种方式,使用TypeReference类,由于其构造方法使用protected进行修饰,故创建其子类
  2. Teacher teacher = JSONObject.parseObject(COMPLEX_JSON_STR, new TypeReference() {});
  3. System.out.println(teacher);
  4. //第二种方式,使用Gson思想
  5. Teacher teacher1 = JSONObject.parseObject(COMPLEX_JSON_STR, Teacher.class);
  6. System.out.println(teacher1);

JavaList → JsonArray

  1. //方式一
  2. String jsonString = JSONArray.toJSONString(students);
  3. JSONArray jsonArray = JSONArray.parseArray(jsonString);
  4. //方式二
  5. JSONArray jsonArray1 = (JSONArray) JSONArray.toJSON(students);

JsonArray 到 JavaList

  1. //已知JsonArray
  2. JSONArray jsonArray = JSONArray.parseArray(JSON_ARRAY_STR);
  3. //第一种方式,使用TypeReference类,由于其构造方法使用protected进行修饰,故创建其子类
  4. ArrayList students = JSONArray.parseObject(jsonArray.toJSONString(),new TypeReference<ArrayList>() {});
  5. //第二种方式,使用Gson的思想
  6. List students1 = JSONArray.parseArray(jsonArray.toJSONString(), Student.class);

其他

JSON 字符串转为 JSON 对象的时候,为了保证其顺序性,需要增加 Feature.OrderedField

  1. Map<String, QuestionTreeVo> map = JSON.parseObject(dataString, Map.class, Feature.OrderedField);