您当前的位置: 首页 >  json

梁云亮

暂无认证

  • 1浏览

    0关注

    1211博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

使用Gson处理JSON数据

梁云亮 发布时间:2019-10-16 12:51:14 ,浏览量:1

Java JSON数据处理技术 之 Gson
  • Maven依赖

      
          com.google.code.gson
          gson
          2.8.6
      
    
  • 操作实体类:

public class Dept {
    private Integer deptno;
    private String dname;
    private String loc;

    public Dept() {
    }

    public Dept(Integer deptno, String dname, String loc) {
        this.deptno = deptno;
        this.dname = dname;
        this.loc = loc;
    }

    public Integer getDeptno() {
        return deptno;
    }

    public void setDeptno(Integer deptno) {
        this.deptno = deptno;
    }

    public String getDname() {
        return dname;
    }

    public void setDname(String dname) {
        this.dname = dname;
    }

    public String getLoc() {
        return loc;
    }

    public void setLoc(String loc) {
        this.loc = loc;
    }

    @Override
    public String toString() {
        return "Dept{" +
                "deptno=" + deptno +
                ", dname='" + dname + '\'' +
                ", loc='" + loc + '\'' +
                '}';
    }
}
示例1:简单Java对象的序列化和反序列化
public static void main(String[] args) {
    Gson gson = new Gson();

    Dept dept = new Dept(10, "RESEARCH", "NEWYORK");

    //序列化
    String json = gson.toJson(dept);
    System.out.println(json);

    //反序列化
    Dept dept2 = gson.fromJson(json, Dept.class);
    System.out.println(dept2);
}
示例2:数组序列化与反序列化
public static void main(String[] args) {
    Gson gson = new Gson();

    String[] array = {"zhangsan","lisi","wanger","mazi"};

    String json = gson.toJson(array);
    System.out.println(json);

    String[] res = gson.fromJson(json, String[].class);
    for (String item : res) {
        System.out.println(item);
    }
}
示例3:List与Set序列化与反序列化
  • 代码一:
public static void main(String[] args) {
    Gson gson = new Gson();

    List list = new ArrayList();
    Collections.addAll(list, "zhangsan", "lisi", "wanger", "mazi");

    String json = gson.toJson(list);//序列化
    System.out.println(json);

    Type type = new TypeToken() {}.getType();
    List res = gson.fromJson(json, type); //反序列化

    res.forEach(System.out::println);
}
  • 代码二:
public static void main(String[] args) {
    Gson gson = new Gson();

    List depts = new ArrayList();
    depts.add(new Dept(10,"ACCOUNTING","NEWYORK"));
    depts.add(new Dept(20,"RESEARCH","DALLAS"));
    depts.add(new Dept(30,"SALES","CHICAGO"));
    depts.add(new Dept(40,"OPERATIONS","BOSTON"));

    String json = gson.toJson(depts);//序列化
    System.out.println(json);

    Type type = new TypeToken() {}.getType();
    List res = gson.fromJson(json, type); //反序列化

    res.forEach(System.out::println);
}

Set与List相同,示例略。

示例4:Map序列化与反序列化

```java
public static void main(String[] args) {
        Gson gson = new Gson();

        Map map = new HashMap();
        map.put("accounting",new Dept(10,"ACCOUNTING","NEWYORK"));
        map.put("research",new Dept(20,"RESEARCH","DALLAS"));
        map.put("sales",new Dept(30,"SALES","CHICAGO"));
        map.put("operations",new Dept(40,"OPERATIONS","BOSTON"));


        String json = gson.toJson(map);//序列化
        System.out.println(json);

        Type type = new TypeToken() {}.getType();
        Map res = gson.fromJson(json, type); //反序列化

        res.forEach((k,v)-> System.out.println(k+" : "+v));
    }
示例5(高级):通过注解指定序列化或不序列化的字段
  • 实体类:
public class Dept {
    @Expose //参与序列化与反序列化
    @SerializedName("no") //指定序列化反序列化的名称
    private Integer deptno;
    @Expose(serialize = false, deserialize = false)
    //不参与序列化,也不参与反序列化
    private String dname;
    @Expose(serialize = false)
    private String loc; //只参与反序列化

    public Dept() {
    }

    public Dept(Integer deptno, String dname, String loc) {
        this.deptno = deptno;
        this.dname = dname;
        this.loc = loc;
    }

    public Integer getDeptno() {
        return deptno;
    }

    public void setDeptno(Integer deptno) {
        this.deptno = deptno;
    }

    public String getDname() {
        return dname;
    }

    public void setDname(String dname) {
        this.dname = dname;
    }

    public String getLoc() {
        return loc;
    }

    public void setLoc(String loc) {
        this.loc = loc;
    }

    @Override
    public String toString() {
        return "Dept{" +
                "deptno=" + deptno +
                ", dname='" + dname + '\'' +
                ", loc='" + loc + '\'' +
                '}';
    }
}
  • 测试代码:
public static void main(String[] args) {
    GsonBuilder builder = new GsonBuilder();
    builder.excludeFieldsWithoutExposeAnnotation();
    Gson gson = builder.create();

    Dept dept = new Dept(10, "ACCOUNTING", "NEWYORK");
    String json = gson.toJson(dept, Dept.class);
    System.out.println(json);

    String data = "{'deptno':40,'dname':'OPERATIONS','loc':'BOSTON'}";
    Dept res = gson.fromJson(data, Dept.class);
    System.out.println(res);
}
示例6(高级):日期格式序列化或反序列化
  • 实体类
public class Stu {
    private int id;
    private Name name;
    private Date birth;

    public Stu() {
    }

    public Stu(int id, Name name, Date birth) {
        this.id = id;
        this.name = name;
        this.birth = birth;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Name getName() {
        return name;
    }

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

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    @Override
    public String toString() {
        return "Stu{" +
                "id=" + id +
                ", name=" + name +
                ", birth=" + birth +
                '}';
    }

    public static class Name{
        private String firstName;
        private String lastName;

        public Name() {
        }

        public Name(String firstName, String lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }

        public String getFirstName() {
            return firstName;
        }

        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }

        public String getLastName() {
            return lastName;
        }

        public void setLastName(String lastName) {
            this.lastName = lastName;
        }

        @Override
        public String toString() {
            return "Name{" +
                    "firstName='" + firstName + '\'' +
                    ", lastName='" + lastName + '\'' +
                    '}';
        }
    }

}
  • 测试代码
public static void main(String[] args) {
    Gson gson1 = new Gson();

    Stu stu = new Stu(1001, new Stu.Name("zhang", "san"), null);

    String json1 = gson1.toJson(stu);//Gson默认情况下不会导出值为null的键
    System.out.println(json1);

    stu = new Stu(1001, new Stu.Name("zhang", "san"), new Date());

    String json2 = gson1.toJson(stu); //内部类会序列化,日期格式默认
    System.out.println(json2);

    stu = new Stu(1001, null, new Date());
    Gson gson = new GsonBuilder()
            .serializeNulls()    //序列化null
            .setDateFormat("yyyy-MM-dd") // 设置日期时间格式,在序列化和反序化时均生效
            .generateNonExecutableJson()//生成不可执行的Json,在最前面加上)]}'
            .disableHtmlEscaping() //禁止转义html标签
            .setPrettyPrinting() //格式化输出
            .create();
    String json3 = gson.toJson(stu);
    System.out.println(json3);
}
关注
打赏
1665409997
查看更多评论
立即登录/注册

微信扫码登录

0.0431s