使用GSON对JSON解析

一.导入GSON
可以用maven,或者网上下载同名包

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

二.生成对应class
要解析json,必须建立要对应的类,如果你用的是IDEA编译器,直接在File -> Settings -> Plugins -> Marketplace安装GsonFormat
,新建一个储存对应的类,Code ->Generate… -> GsonFormat,这样可以自动生成代码,例如要解析这样的json是这样的:

{"no":3037,"openid":"1111111","jing":100.61225,"wei":46.42034,"uptime":"Feb 15, 2020 7:18:33 PM"}

那么代码就是这样的:

public class test1 {

    private int no;
    private String openid;
    private double jing;
    private double wei;
    private String uptime;

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public String getOpenid() {
        return openid;
    }

    public void setOpenid(String openid) {
        this.openid = openid;
    }

    public double getJing() {
        return jing;
    }

    public void setJing(double jing) {
        this.jing = jing;
    }

    public double getWei() {
        return wei;
    }

    public void setWei(double wei) {
        this.wei = wei;
    }

    public String getUptime() {
        return uptime;
    }

    public void setUptime(String uptime) {
        this.uptime = uptime;
    }
}

三.获取数据
完成如上操作后,就可以进行下一步解析gson数据了,例如:

		Gson gson = new Gson(); //新建gson
        test1 Result_bean = gson.fromJson(obstr, test1.class); //gson与工具类绑定,obstr为要解析的jsonobject
        double jing = Result_bean.getJing();
        System.out.println(jing);

你可能感兴趣的:(使用GSON对JSON解析)