1,记录一下JSON使用
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import java.util.ArrayList;
import java.util.List;
public class JsonTest {
public static void main(String[] args) {
List<Student> list = new ArrayList<>();
Student student1 = new Student ("提莫",12);
Student student2 = new Student ("金克斯",16);
list.add(student1);
list.add(student2);
ClassRoom classRoom = new ClassRoom("1号教室",list);
// java普通对象转化为json对象 ,方式一
JSON studentJson1 = (JSON) JSON.toJSON(student1);
System.out.println(studentJson1);//{"name":"提莫","age":12}
//java普通对象转化为json对象 ,方式二
String clssRoomJsonStr = JSON.toJSONString(classRoom);
JSON classRoomJson2 = JSON.parseObject(clssRoomJsonStr);
System.out.println(classRoomJson2);//{"ls":[{"name":"提莫","age":12},{"name":"金克斯","age":16}],"name":"1号教室"}
// java集合对象转jsonArray对象, 方式一
JSON listrJson1 = (JSON) JSON.toJSON(list);
System.out.println(listrJson1);//[{"name":"提莫","age":12},{"name":"金克斯","age":16}]
//java集合对象转化为jsonArray对象 ,方式二
String listJsonStr = JSON.toJSONString(list);
JSONArray listJson2 = JSON.parseArray(listJsonStr);
System.out.println(listJson2);//[{"name":"提莫","age":12},{"name":"金克斯","age":16}]
// json对象解析为java普通对象
Student student = JSON.parseObject(String.valueOf(studentJson1),Student.class);
System.out.println(student);//Student{name='提莫', age=12}
ClassRoom classRoom1 = JSON.parseObject(clssRoomJsonStr,ClassRoom.class);
System.out.println(classRoom1);//ClassRoom{name='1号教室', ls=[Student{name='提莫', age=12}, Student{name='金克斯', age=16}]}
// json对象解析为java集合对象
List<Student> ls1 = JSON.parseArray(String.valueOf(listrJson1),Student.class);
System.out.println(ls1);//[Student{name='提莫', age=12}, Student{name='金克斯', age=16}]
List<Student> ls2 = JSON.parseArray(listJsonStr,Student.class);
System.out.println(ls2);//[Student{name='提莫', age=12}, Student{name='金克斯', age=16}]
}
}