java json字符串、json、java对象之间的转换关系

1、json转json字符串

JSONObject json = null;
json = new JSONObject(); 
json.put("responseCode", "1");
String str = json.toString();

2、java对象转json对象

JSONObject object = JSONObject.fromObject(user);

3、java 对象列表(list)转换为json对象数组,并转为字符串

JSONArray array = JSONArray.fromObject(list);
String str= array.toString();

4、把json字符串转换为java对象数组

JSONArray json = JSONArray.fromObject(userStr);//userStr是json字符串
List<User> users= (List<User>)JSONArray.toCollection(json, User.class);

5、把json字符串转换为java 对象

public static void jsonStrToJava(){
        //定义两种不同格式的字符串
        String objectStr="{\"name\":\"JSON\",\"age\":\"24\",\"address\":\"北京市西城区\"}";
        String arrayStr="[{\"name\":\"JSON\",\"age\":\"24\",\"address\":\"北京市西城区\"}]";
    
        //1、使用JSONObject
        JSONObject jsonObject=JSONObject.fromObject(objectStr);
        Student stu=(Student)JSONObject.toBean(jsonObject, Student.class);
        
        //2、使用JSONArray
        JSONArray jsonArray=JSONArray.fromObject(arrayStr);
        //获得jsonArray的第一个元素
        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);
        
    }

猜你喜欢

转载自blog.csdn.net/qq_43072912/article/details/84105046