gson解析json

来源:互联网 发布:怎样建数据库 编辑:程序博客网 时间:2024/06/07 01:00

为什么使用Gson

Gson是google一个比较流行的开源项目,相比于json,Gson的功能更加全面,性能更加强大,使用方式也更加便捷简单。

一般使用Gson生成json。

 

Gson读取

相比于用JSONObject实现Json,借助Gson具有更多的优势,更加便捷,如下常用的几方面:

1.注解序列化属性

给bean中类的某个属性加上注解,序列化某个属性,可以加上别名,更加安全,不易出错。

public class DaShen {   @SerializedName("NAME")   private Stringname;   private Stringschool;   private boolean has_girlfriend;   private double age;   private Objectcar;   private Objecthouse;   private String[]major;   private Stringcomment;   private String birthday;}

         如上所示,给属性name加上注解,则返回的是NAME.

实现:    

  DaShen terence=new DaShen();      terence.setName("terence");      terence.setAge(25.9);      terence.setBirthday("1990-5-9");      terence.setSchool("HDU");      terence.setMajor(new String[]{"Computer","qiqiqiqi","装B"});      terence.setHas_girlfriend(false);      terence.setComment("sha,sha,sha,sha……");      terence.setCar(null);      terence.setHouse(null);      terence.setIgnore("请把我忽略掉,beng……sah ka la ka");      Gson gson=new Gson();      System.out.println(gson.toJson(terence));


2 利用Gson格式化Json

可以利用Gson的GsonBuilder类设置规范化的格式(setPrettyPrinting),然后利用该类的create()方法创建gson,从而转化为json,这样呈现出来的json数据直接就是规范化的格式,看着更好。     

      GsonBuilder gsonBuilder=new GsonBuilder();      gsonBuilder.setPrettyPrinting();//设置出漂亮的格式      Gsongson2=gsonBuilder.create();      System.out.println(gson2.toJson(terence));

结果

{

  "NAME":"terence",

  "school":"HDU",

  "has_girlfriend": false,

  "age": 25.9,

  "major": [

    "Computer",

    "qiqiqiqi",

    "装B"

  ],

  "comment":"sha,sha,sha,sha……",

  "birthday": "1990-5-9"

}

3.利用GSON生成新的策略

可以利用Gson生成新的策略,通过带入回调函数添加额外功能,生成个性化的json,很显然,JSONObject不具备这样的功能。

GsonBuilder gsonBuilder=new GsonBuilder();

gsonBuilder.setPrettyPrinting();       

//利用Gson生成一个新的策略,生成个性化的json

//传给这个策略一个回调函数,通过回调函数添加一些额外的功能

//如下所示的策略,给age属性一个新的别名AGE

   gsonBuilder.setFieldNamingStrategy(new FieldNamingStrategy()        {            public String translateName(Field f)            {                if(f.getName().equals("age"))                    return"AGE";                else                    return f.getName();            }        });Gson gson3=gsonBuilder.create();System.out.println(gson3.toJson(terence));

 

4.隐藏/排除属性

在bean中,用关键字transient修饰的属性用Gson转换成Json后可隐藏改属性。

public class DaShen {   private Objectcar;   private Objecthouse;   private String[]major;   private Stringcomment;   private Stringbirthday;   public transient String ignore;}

     该类中的属性igore在json中不可显示。

 

Gson解析

       使用Gson可以实现双向生成,不仅可以用Bean生成Json,还可以用Json生成Bean.

                                              

1.利用GSON逆向解析生成Bean

直接利用GSON的fromJson()方法将其转化为bean;

File file=newFile(ReadJsonSample.class.getResource("/data/terence.json").getFile());String content =FileUtils.readFileToString(file);Gson gson=new Gson();DaShen terence=gson.fromJson(content, DaShen.class);System.out.println(terence.toString());

集合类的无缝对接和日期转换

         利用google的Gson逆向解析Json,可以将Json中的数组自动映射到Bean中的集合,无论是List还是Set,都不需要做额外的事,会自动实现无缝对接。

        File file=new File(ReadJsonSample.class.getResource("/data/terence.json").getFile());        String content =FileUtils.readFileToString(file);

//设置日期格式

Gson g=new GsonBuilder().setDateFormat("yyyy-MM-dd").create();     DiaoSi wang=g.fromJson(content, DiaoSi.class);System.out.println(wang.getBirthday().toLocaleString());

 

//不管是List还是Set,都会自动转化,不需要做额外的辅助,直接输出就可以看到了

System.out.println(wang.getClass());

System.out.println(wang.getMajor());

System.out.println(wang.getMajor().getClass());

结果


 

JSON库总结


       功能:映射JavaObject与json格式数据

 

  • 可通过Annotation,注解来声明。
  • 支持自定义属性名称。
  • 支持包含或排除属性
  • 支持自定义接口自己完成解析/生成过程。

参考代码

Reference demo:testJson

0 0
原创粉丝点击