把实体类对象转成json格式
//1、使用JSONObject
JSONObject json = JSONObject.fromObject(stu);
//2、使用JSONArray
JSONArray array=JSONArray.fromObject(stu);
把JSON字符串格式转化为java对象
public static void jsonStrToJava(){
String objectStr="{\"name\":\"JSON\",\"age\":\"24\",\"address\":\"北京市西城区\"}";
String arrayStr="[{\"name\":\"JSON\",\"age\":\"24\",\"address\":\"北京市西城区\"}]";
JSONObject jsonObject=JSONObject.fromObject(objectStr);
Student stu=(Student)JSONObject.toBean(jsonObject, Student.class);
JSONArray jsonArray=JSONArray.fromObject(arrayStr);
Object o=jsonArray.get(0);
JSONObject jsonObject2=JSONObject.fromObject(o);
Student stu2=(Student)JSONObject.toBean(jsonObject2, Student.class);
System.out.println("stu:"+stu);
System.out.println("stu2:"+stu2);
}
list–》》json字符串
public static void listToJSON(){
Student stu=new Student();
stu.setName("JSON");
stu.setAge("23");
stu.setAddress("北京市海淀区");
List<Student> lists=new ArrayList<Student>();
lists.add(stu);
JSONArray listArray=JSONArray.fromObject(lists);
System.out.println("listArray:"+listArray.toString());
}
json字符串–》》list
public static void jsonToList(){
String arrayStr="[{\"name\":\"JSON\",\"age\":\"24\",\"address\":\"北京市西城区\"}]";
List<Student> list2=(List<Student>)JSONArray.toList(JSONArray.fromObject(arrayStr), Student.class);
for (Student stu : list2) {
System.out.println(stu);
}
Student[] ss =(Student[])JSONArray.toArray(JSONArray.fromObject(arrayStr),Student.class);
for (Student student : ss) {
System.out.println(student);
}
}
map–》》json字符串
public static void mapToJSON(){
Student stu=new Student();
stu.setName("JSON");
stu.setAge("23");
stu.setAddress("中国上海");
Map<String,Student> map=new HashMap<String,Student>();
map.put("first", stu);
JSONObject mapObject=JSONObject.fromObject(map);
System.out.println("mapObject"+mapObject.toString());
JSONArray mapArray=JSONArray.fromObject(map);
System.out.println("mapArray:"+mapArray.toString());
}
json字符串–》》map
public static void jsonToMap(){
String strObject="{\"first\":{\"address\":\"中国上海\",\"age\":\"23\",\"name\":\"JSON\"}}";
JSONObject jsonObject=JSONObject.fromObject(strObject);
Map map=new HashMap();
map.put("first", Student.class);
System.out.println(my.getFirst());
}