String → JSONObject
public static JSONObject parseObject(String text)
// eg:
JSONObject jsonObject = JSON.parseObject(result);
String → Java对象
public static T parseObject(String text, Class clazz)
// eg:
BaseVo question = JSON.parseObject(result, BaseVo.class);
复合型结构:
public static <T> T parseObject(String text, TypeReference<T> type, Feature... features)
// String → map<String,Object> 如:{"code":"1","question":{"queId":"123"}}
HashMap<String,QuestionBaseVo> map =JSON.parseObject(result, new TypeReference<HashMap<String,QuestionBaseVo>>(){});
// String → List<List<Object>> 如:[[{"queId":"123"}]]
List<List<BaseVo>> list = JSON.parseObject(result, new TypeReference<List<List<BaseVo>>>(){});
JSONObject → json字符串
String jsonString = jsonObject.toJSONString();
json 字符串 → 数组类型到 JSONArray 的转换
JSONArray jsonArray = JSONArray.parseArray(JSON_ARRAY_STR);
JSONArray → json 字符串
//已知JSONArray,目标要转换为json字符串
JSONArray jsonArray = JSONArray.parseArray(JSON_ARRAY_STR);
String jsonString = JSONArray.toJSONString(jsonArray);
JavaBean → json字符串
Student student = new Student("lily", 12);
String jsonString = JSONObject.toJSONString(student);
json 字符串 → JavaBean_List 的转换
// 第一种方式,使用TypeReference类,由于其构造方法使用protected进行修饰,故创建其子类
List studentList = JSONArray.parseObject(JSON_ARRAY_STR, new TypeReference<ArrayList>() {});
System.out.println("studentList: " + studentList);
// 第二种方式,使用Gson的思想
List studentList1 = JSONArray.parseArray(JSON_ARRAY_STR, Student.class);
System.out.println("studentList1: " + studentList1);
List → json字符串
List students = new ArrayList();
String jsonString = JSONArray.toJSONString(students);
复杂 json 格式字符串 → javaBean
//第一种方式,使用TypeReference类,由于其构造方法使用protected进行修饰,故创建其子类
Teacher teacher = JSONObject.parseObject(COMPLEX_JSON_STR, new TypeReference() {});
System.out.println(teacher);
//第二种方式,使用Gson思想
Teacher teacher1 = JSONObject.parseObject(COMPLEX_JSON_STR, Teacher.class);
System.out.println(teacher1);
JavaList → JsonArray
//方式一
String jsonString = JSONArray.toJSONString(students);
JSONArray jsonArray = JSONArray.parseArray(jsonString);
//方式二
JSONArray jsonArray1 = (JSONArray) JSONArray.toJSON(students);
JsonArray 到 JavaList
//已知JsonArray
JSONArray jsonArray = JSONArray.parseArray(JSON_ARRAY_STR);
//第一种方式,使用TypeReference类,由于其构造方法使用protected进行修饰,故创建其子类
ArrayList students = JSONArray.parseObject(jsonArray.toJSONString(),new TypeReference<ArrayList>() {});
//第二种方式,使用Gson的思想
List students1 = JSONArray.parseArray(jsonArray.toJSONString(), Student.class);
其他
JSON 字符串转为 JSON 对象的时候,为了保证其顺序性,需要增加 Feature.OrderedField
Map<String, QuestionTreeVo> map = JSON.parseObject(dataString, Map.class, Feature.OrderedField);