package com.example.demo.json;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.example.demo.common.Person;
public class JsonLib {
private static final String JSON_OBJ_STR = "{\"studentName\":\"lily\",\"studentAge\":12}";
private static final String JSON_ARRAY_STR = "[{\"studentName\":\"lily\",\"studentAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]";
private static final String COMPLEX_JSON_STR = "{\"teacherName\":\"crystall\",\"teacherAge\":27,\"course\":{\"courseName\":\"english\",\"code\":1270},\"students\":[{\"studentName\":\"lily\",\"studentAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]}";
@SuppressWarnings("unchecked")
public static void main(String[] args) {
testComplexJSONStrToJSONObject();
}
public static void testComplexJSONStrToJSONObject(){
System.out.println(COMPLEX_JSON_STR);
JSONObject jsonObject = JSON.parseObject(COMPLEX_JSON_STR);
System.out.println(jsonObject);
String teacherName = jsonObject.getString("teacherName");
Integer teacherAge = jsonObject.getInteger("teacherAge");
JSONObject course = jsonObject.getJSONObject("course");
JSONArray students = jsonObject.getJSONArray("students");
System.out.println(teacherName+"------"+teacherAge+"===json对象===="+course+"----json数组----"+students);
JSONArray jsonArray = JSON.parseArray(students.toString());
System.out.println(jsonArray);
}
public static void testJSONStrToJSONArray(){
JSONArray jsonArray = JSON.parseArray(JSON_ARRAY_STR);
int size = jsonArray.size();
for (int i = 0; i < size; i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
System.out.println(jsonObject.getString("studentName")+":"+jsonObject.getInteger("studentAge"));
}
for (Object obj : jsonArray) {
JSONObject jsonObject = (JSONObject) obj;
System.out.println(jsonObject.getString("studentName")+":"+jsonObject.getInteger("studentAge"));
}
}
public static void testJSONStrToJSONObject(){
JSONObject jsonObject = JSON.parseObject(JSON_OBJ_STR);
System.out.println(jsonObject.getString("studentName")+":"+jsonObject.getInteger("studentAge"));
}
public static void demoJson() {
String str = "{\"name\":\"Tom\",\"age\":90}";
JSONObject jsonObject = JSONObject.parseObject(str);
Map<String, String> params = JSONObject.parseObject(jsonObject.toString(), new TypeReference<Map<String, String>>(){});
System.out.println(params);
str = "{\"id\":\"A001\",\"name\":\"Jack\"}";
jsonObject = JSONObject.parseObject(str);
System.out.println(jsonObject);
Person person = JSON.parseObject(str, new TypeReference<Person>() {});
System.out.println(person.toString());
}
}