学习 JSON.parseObject 和 JSON.toJSONString 一篇文章就够了

2年前 (2022) 程序员胖胖胖虎阿
283 0 0

JSON.parseObject 是将Json字符串转化为相应的对象;

JSON.toJSONString 是将对象转化为Json字符串

两者主要用于前后台的数据传输过程中

使用前需要先导入该包:

<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
    <version>1.2.62</version>
</dependency>

文章目录

    • 一、JSON.parseObject
    • 二、JSON.toJSONString
    • 三、JSON.parseObject 的其他几种使用

一、JSON.parseObject

将JSON字符串转为Bean对象

Java 对象 Student

@Data
@Accessors(chain = true)
public class Student {
    private String name;
    private int score;
}

将JSON字符串转为该对象

public class Main {
    public static void main(String[] args) {
        String jsonStudent = "{name:'yolo',score:90}";
        Student student = JSON.parseObject(jsonStudent, Student.class);
        System.out.println(student);
    }
}

二、JSON.toJSONString

是将对象转化为Json字符串

public class Main {
    public static void main(String[] args) {
        Student student = new Student().setName("yolo").setScore(98);
        String s = JSON.toJSONString(student);
        System.out.println(s);
    }
}

三、JSON.parseObject 的其他几种使用

示例1:str = “{“name”:“Yolo”,“Address”:“Beijing”}”;

public class Main {
    public static void main(String[] args) {
        String str = "{\"name\":\"Yolo\",\"Address\":\"Beijing\"}";
        JSONObject jsonObject = JSON.parseObject(str);
        System.out.println(jsonObject.toString());
        System.out.println(jsonObject.getString("name"));
        System.out.println(str);
    }
}

学习 JSON.parseObject 和 JSON.toJSONString 一篇文章就够了
示例2:str2 = “{“name”:“Yolo”,“Address”:“Beijing”, “data”:{“id”: 123}}”

public class Main {
    public static void main(String[] args) {
        String str2 = "{\"name\":\"Yolo\",\"Address\":\"Beijing\", \"data\":{\"id\": 123}}";
        JSONObject jsonObject2 = JSON.parseObject(str2);
        System.out.println(jsonObject2.getString("data"));
        System.out.println(JSON.parseObject(jsonObject2.getString("data")).getString("id"));
    }
}

学习 JSON.parseObject 和 JSON.toJSONString 一篇文章就够了
示例3:str3 = “{“name”:“Yolo”,“Address”:“Beijing”, “data”:[{“id”: 123},{“id”: 345}]}”;

public class Main {
    public static void main(String[] args) {
        String str3 = "{\"name\":\"Yolo\",\"Address\":\"Beijing\", \"data\":[{\"id\": 123},{\"id\": 345}]}";
        JSONObject jsonObject3 = JSON.parseObject(str3);
        System.out.println(jsonObject3.toString());
        System.out.println(jsonObject3.toJSONString());
        System.out.println("data " + jsonObject3.getString("data"));
        JSONArray data = JSON.parseArray(jsonObject3.getString("data"));
        for (Object d: data) {
            System.out.println(d);
            System.out.println(JSON.parseObject(d.toString()).getString("id"));
            System.out.println(JSON.parseObject(String.valueOf(d)).getString("id"));
        }
    }
}

学习 JSON.parseObject 和 JSON.toJSONString 一篇文章就够了

相关文章

暂无评论

暂无评论...