Gson的生成与解析

Gson的生成

使用maven引入依赖

<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.2</version>
        </dependency>

实体类User

package json;

import com.google.gson.annotations.SerializedName;

import java.util.Arrays;

public class User {
    private String name;
    private Integer age;
    private boolean has_car;
    private Object has_girlfriend;
    private String[] major;
    private Grade[] grades;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public boolean isHas_car() {
        return has_car;
    }

    public void setHas_car(boolean has_car) {
        this.has_car = has_car;
    }

    public Object getHas_girlfriend() {
        return has_girlfriend;
    }

    public void setHas_girlfriend(Object has_girlfriend) {
        this.has_girlfriend = has_girlfriend;
    }

    public String[] getMajor() {
        return major;
    }

    public void setMajor(String[] major) {
        this.major = major;
    }

    public Grade[] getGrades() {
        return grades;
    }

    public void setGrades(Grade[] grades) {
        this.grades = grades;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", has_car=" + has_car +
                ", has_girlfriend=" + has_girlfriend +
                ", major=" + Arrays.toString(major) +
                ", grades=" + Arrays.toString(grades) +
                '}';
    }
}

代码:

package gson;


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import json.Grade;
import json.User;

public class FirstGSON {

    public static void main(String[] args)
    {

        System.out.println("methed1:");
        methed1();
        System.out.println("methed2:");
        methed2();
    }


    public static void methed1()
    {
        User user = new User();
        user.setName("张三");
        user.setAge(19);
        user.setHas_car(true);
        user.setHas_girlfriend(null);
        user.setMajor(new String[]{"C","Java"});
        user.setGrades(new Grade[]{new Grade("C",80),new Grade("Java",85)});
        Gson gson = new Gson();
        System.out.println(gson.toJson(user));
    }

    //美化输出结果
    public static void methed2()
    {
        User user = new User();
        user.setName("张三");
        user.setAge(19);
        user.setHas_car(true);
        user.setHas_girlfriend(null);
        user.setMajor(new String[]{"C","Java"});
        user.setGrades(new Grade[]{new Grade("C",80),new Grade("Java",85)});

        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setPrettyPrinting();
        Gson gson = gsonBuilder.create();
        System.out.println(gson.toJson(user));
    }


}

运行结果

methed1:
{"name":"张三","age":19,"has_car":true,"major":["C","Java"],"grades":[{"object":"C","grade":80},{"object":"Java","grade":85}]}
methed2:
{
  "name": "张三",
  "age": 19,
  "has_car": true,
  "major": [
    "C",
    "Java"
  ],
  "grades": [
    {
      "object": "C",
      "grade": 80
    },
    {
      "object": "Java",
      "grade": 85
    }
  ]
}

@SerializedName 的使用

有上面可知,实体类User的属性与生成的json的字段是一一对应的。如果不想一一对应,则可以在实体类属性上加上@SerializedName注解

比如

@SerializedName("NAME")
    private String name;

运行结果

{"NAME":"张三","age":19,"has_car":true,"major":["C","Java"],"grades":[{"object":"C","grade":80},{"object":"Java","grade":85}]}

Gson的解析

首先在工程目录"src/main/java"下创建一个json文件,用于解析。

demo.json

{"has_car":true,
  "major":["C","Java"],
  "name":"张三",
  "grades":[
              {"grade":80,"object":"C"},
              {"grade":85,"object":"Java"}
            ],
  "age":19}
代码
package gson;

import com.google.gson.Gson;
import json.User;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

public class ReadGson {

    public static void main(String[] args) throws IOException
    {
        //读取文件
        File file = new File("src/main/java/demo.json");
        String content = FileUtils.readFileToString(file);
        Gson gson = new Gson();
        User user = gson.fromJson(content,User.class);
        System.out.println(user.toString());
    }
}

运行结果
User{name='张三', age=19, has_car=true, has_girlfriend=null, major=[C, Java], grades=[Grade{object='C', grade=80}, Grade{object='Java', grade=85}]}


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值