美文网首页程序员
GSON使用介绍

GSON使用介绍

作者: 九命丿相柳 | 来源:发表于2017-07-23 18:37 被阅读0次

    Gson介绍

    Gson(又称Google Gson)是Google公司发布的一个开放源代码的Java库,主要用途为序列化Java对象为JSON字符串,或反序列化JSON字符串成Java对象。而JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成,广泛应用于各种数据的交互中,尤其是服务器与客户端的交互。

    下载地址:Gson

    对象转JSON

    单独转一个对象

    Article item;
    Gson gson = new Gson();
    String result = gson.toJson(item);
    

    输出结果:

    {"id":1,"uuid":"868621d3-d55d-486e-bd7e-1f2df5ec4746","title":"Update Test Title","categories":"Update Test Categories","tags":"Update Test Tags","createTime":"May 23, 2017 11:38:38 PM","updateTime":"May 24, 2017 9:46:46 PM","enable":true}
    

    转一组对象

    List<Article> items;
    Gson gson = new Gson();
    String result = gson.toJson(items);
    

    输出结果:

    {"[{"id":1,"uuid":"868621d3-d55d-486e-bd7e-1f2df5ec4746","title":"Update Test Title","categories":"Update Test Categories","tags":"Update Test Tags","createTime":"May 23, 2017 11:38:38 PM","updateTime":"May 24, 2017 9:46:46 PM","enable":true},{"id":2,"uuid":"e58d3d06-8a40-4d64-9329-7a4be87ba1dc","title":"Test Title","categories":"Test Categories","tags":"Test Tags","createTime":"May 23, 2017 11:44:41 AM","updateTime":"May 23, 2017 11:44:41 AM","enable":true},{"id":3,"uuid":"bb662958-398d-4d53-b7c6-9738832b0781","title":"Test Title","categories":"Test Categories","tags":"Test Tags","createTime":"May 23, 2017 8:42:01 PM","updateTime":"May 23, 2017 8:42:01 PM","enable":true}]
    

    设置日期时间格式

    List<Article> items;
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setDateFormat("yyyy-MM-dd HH:mm:ss");
    Gson gson = gsonBuilder.create();
    String result = gson.toJson(items);
    

    输出结果:

    [{"id":1,"uuid":"868621d3-d55d-486e-bd7e-1f2df5ec4746","title":"Update Test Title","categories":"Update Test Categories","tags":"Update Test Tags","createTime":"2017-05-23 23-38-38","updateTime":"2017-05-24 21-46-46","enable":true},{"id":2,"uuid":"e58d3d06-8a40-4d64-9329-7a4be87ba1dc","title":"Test Title","categories":"Test Categories","tags":"Test Tags","createTime":"2017-05-23 11-44-41","updateTime":"2017-05-23 11-44-41","enable":true},{"id":3,"uuid":"bb662958-398d-4d53-b7c6-9738832b0781","title":"Test Title","categories":"Test Categories","tags":"Test Tags","createTime":"2017-05-23 20-42-01","updateTime":"2017-05-23 20-42-01","enable":true}]
    

    隐藏某些域

    List<Article> items;
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setExclusionStrategies(new ExclusionStrategy() {
        @Override
        public boolean shouldSkipField(FieldAttributes fieldAttributes) {
            String[] skipFields = {"enable"};
            String field = fieldAttributes.getName().toLowerCase();
            for (String skipField : skipFields)
                if (field.equals(skipField))
                    return true;
            return false;
        }
        @Override
        public boolean shouldSkipClass(Class<?> aClass) {
            return false;
        }
    });
    Gson gson = gsonBuilder.create();
    String result = gson.toJson(items);
    

    输出结果:

    [{"id":1,"uuid":"868621d3-d55d-486e-bd7e-1f2df5ec4746","title":"Update Test Title","categories":"Update Test Categories","tags":"Update Test Tags","createTime":"2017-05-23 23:38:38","updateTime":"2017-05-24 21:46:46"},{"id":2,"uuid":"e58d3d06-8a40-4d64-9329-7a4be87ba1dc","title":"Test Title","categories":"Test Categories","tags":"Test Tags","createTime":"2017-05-23 11:44:41","updateTime":"2017-05-23 11:44:41"},{"id":3,"uuid":"bb662958-398d-4d53-b7c6-9738832b0781","title":"Test Title","categories":"Test Categories","tags":"Test Tags","createTime":"2017-05-23 20:42:01","updateTime":"2017-05-23 20:42:01"}]
    

    JSON转对象

    首先建立JSON对应的对象

    class JsonHolder {
        public boolean success;
        public String uuid;
        public String message;
    }
    

    转单个对象

    编写测试代码

    @Test
    public void testJsonObeject() {
        String uuid = "4b10e722-0699-4590-90d3-0e7e12358518";
        String json = "{\"success\":true, \"uuid\":\"" + uuid + "\"}";
        json = "{\"success\":false, \"message\":\"can't create new file!\"}";
        JsonHolder item = new Gson().fromJson(json, JsonHolder.class);
        System.out.println(item.success);
        System.out.println(item.uuid);
        System.out.println(item.message);
    }
    

    输出结果

    false
    null
    can't create new file!
    

    转一组对象

    编写测试代码

    @Test
    public void testJsonObeject() {
        String uuid = "4b10e722-0699-4590-90d3-0e7e12358518";
        String json = "{\"success\":true, \"uuid\":\"" + uuid + "\"}";
        String longJson = "[" + json + ","  + json + "," + json + "]";
        JsonHolder[] items = new Gson().fromJson(longJson, JsonHolder[].class);
        for (JsonHolder item : items) {
            System.out.println(item.success);
            System.out.println(item.uuid);
            System.out.println(item.message);
        }
    }
    

    转复杂对象

    先给出一个比较复杂的JSON

    {
      "error": 0,
      "status": "success",
      "date": "2014-05-10",
      "results": [
        {
          "currentCity": "南京",
          "weather_data": [
            {
              "date": "周六(今天, 实时:19℃)",
              "dayPictureUrl": "http://api.map.baidu.com/images/weather/day/dayu.png",
              "nightPictureUrl": "http://api.map.baidu.com/images/weather/night/dayu.png",
              "weather": "大雨",
              "wind": "东南风5-6级",
              "temperature": "18℃"
            },
            {
              "date": "周日",
              "dayPictureUrl": "http://api.map.baidu.com/images/weather/day/zhenyu.png",
              "nightPictureUrl": "http://api.map.baidu.com/images/weather/night/duoyun.png",
              "weather": "阵雨转多云",
              "wind": "西北风4-5级",
              "temperature": "21 ~ 14℃"
            }
          ]
        }
      ]
    }
    

    构造接收这个JSON的对象:

    class JsonHolder {
        public int error;
        public String status;
        public String date;
        public A[] results;
        class A {
            public String currentCity;
            public B[] weather_data;
            class B {
                public String date;
                public String dayPictureUrl;
                public String nightPictureUrl;
                public String weather;
                public String wind;
                public String temperature;
            }
        }
    }
    

    编写测试代码

    @Test
    public void testJsonObeject() throws IOException {
        String json = "";
        BufferedReader br = new BufferedReader(new FileReader("/home/alan/Documents/WorkSpace/Intellij_IDEA_workspace/MyBlog/test/json.txt"));
        String line = "";
        while ((line = br.readLine()) != null) {
            json += line;
        }
        br.close();
        JsonHolder jsonHolder = new Gson().fromJson(json, JsonHolder.class);
        System.out.println(jsonHolder.status);
        System.out.println(jsonHolder.results[0].currentCity);
        System.out.println(jsonHolder.results[0].weather_data[1].weather);
        System.out.println(jsonHolder.results[0].weather_data[1].temperature);
    }
    

    输出结果:

    success
    南京
    阵雨转多云
    21 ~ 14℃
    

    相关文章

      网友评论

        本文标题:GSON使用介绍

        本文链接:https://www.haomeiwen.com/subject/rmvmkxtx.html