Gson用法总结

首先注入Gson的依赖

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.6.2</version>
        </dependency>

新建一个实体类Student

@Data
public class Student {
    private Integer id;

    private String name;

    private String sex;
}

建立三个student的测试对象

        Student student1 = new Student();
        student1.setId(1);
        student1.setName("Sam");
        student1.setSex("male");

        Student student2 = new Student();
        student2.setId(2);
        student2.setName("Tom");
        student2.setSex("male");

        Student student3 = new Student();
        student3.setId(3);
        student3.setName("luna");
        student3.setSex("female");

(1)javabean转换为json:

    public static String javabeanToJson(Student student){
        Gson gson = new Gson();
        String json = gson.toJson(student);
        return json;
    }

结果:


(2)将对象数组转化为json

    public static String listToJson(List<Student> students){
        Gson gson = new Gson();
        String json = gson.toJson(students);
        return json;
    }

结果:


(3)map转化为json

    public static String mapToJson(Map<String, Student> map) {
        Gson gson = new Gson();
        String json = gson.toJson(map);
        return json;
    }

结果:


(4)json转换为javabean

    public static void jsonToJavabean(String json) {
        Gson gson = new Gson();
        Student student = gson.fromJson(json, Student.class);
        System.out.println(student.toString());
    }

结果:


(5)json转换为list

    public static void jsonToList(String json) {
        Gson gson = new Gson();
        List<Student> students = gson.fromJson(json, new TypeToken<List<Student>>() {
        }.getType());
        for (Student student : students) {
            System.out.println(student);
        }
    }

结果:


(6)json转换为map

    public static void jsonToMap(String json) {
    Gson gson = new Gson();
    Map<String, Student> maps = gson.fromJson(json, new TypeToken<Map<String, Student>>() {
    }.getType());
    for (Map.Entry<String, Student> map : maps.entrySet()) {
        System.out.println("key: " + map.getKey() + " value: " + map.getValue());
    }

结果:


项目文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值