Java_Gson json的学习

Posted 杨迈1949

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java_Gson json的学习相关的知识,希望对你有一定的参考价值。

转载请注明出处:http://blog.csdn.net/y22222ly/article/details/52213043

Gson基本使用

下面对json做json->object;object->json操作:


    "code": 200,
    "msg": "success",
    "newslist": [
        
            "ctime": "2016-03-31",
            "title": "奇虎360宣布通过私有化决议",
            "description": "互联网头条",
            "picUrl": "http://t1.qpic.cn/mblogpic/f01a972dbcc1060fd456/2000",
            "url": "http://mp.weixin.qq.com/s?__biz=MjM5OTMyODA2MA==&idx=1&mid=402594468&sn=5cd644536b472a283cc1d3f5124a0cab"
        ,
        
            "ctime": "2016-03-31",
            "title": "小本生意做什么挣钱十七大小本生意推荐",
            "description": "创业最前线",
            "picUrl": "http://zxpic.gtimg.com/infonew/0/wechat_pics_-4225297.jpg/640",
            "url": "http://mp.weixin.qq.com/s?__biz=MzA3NjgzNDUwMQ==&idx=2&mid=401864059&sn=cfa082e38ba38c7e673b1ce0a075faee"
        
    ]

首先需要写一个Object类,作为这个json的实体类。这里我使用的IDE为android Studio,使用GsonFormat插件能一键转换为Object对象。自己写的时候,顺着符号``[来写即可,遇到表示该字段为对象,遇到[表明该字段为数组或是集合。
转换后的对象如下
Weather.java

package com.raise.raisestudy.gson.entity;

import java.util.List;

/**
 * Created by raise.yang on 16/08/15.
 */

public class NewsInfo 

    /**
     * code : 200
     * msg : success
     * newslist : ["ctime":"2016-03-31","title":"奇虎360宣布通过私有化决议","description":"互联网头条","picUrl":"http://t1.qpic.cn/mblogpic/f01a972dbcc1060fd456/2000","url":"http://mp.weixin.qq.com/s?__biz=MjM5OTMyODA2MA==&idx=1&mid=402594468&sn=5cd644536b472a283cc1d3f5124a0cab","ctime":"2016-03-31","title":"小本生意做什么挣钱十七大小本生意推荐","description":"创业最前线","picUrl":"http://zxpic.gtimg.com/infonew/0/wechat_pics_-4225297.jpg/640","url":"http://mp.weixin.qq.com/s?__biz=MzA3NjgzNDUwMQ==&idx=2&mid=401864059&sn=cfa082e38ba38c7e673b1ce0a075faee"]
     */

    private int code;
    private String msg;
    /**
     * ctime : 2016-03-31
     * title : 奇虎360宣布通过私有化决议
     * description : 互联网头条
     * picUrl : http://t1.qpic.cn/mblogpic/f01a972dbcc1060fd456/2000
     * url : http://mp.weixin.qq.com/s?__biz=MjM5OTMyODA2MA==&idx=1&mid=402594468&sn=5cd644536b472a283cc1d3f5124a0cab
     */

    private List<NewslistBean> newslist;

    public int getCode() 
        return code;
    

    public void setCode(int code) 
        this.code = code;
    

    public String getMsg() 
        return msg;
    

    public void setMsg(String msg) 
        this.msg = msg;
    

    public List<NewslistBean> getNewslist() 
        return newslist;
    

    public void setNewslist(List<NewslistBean> newslist) 
        this.newslist = newslist;
    

    public static class NewslistBean 
        private String ctime;
        private String title;
        private String description;
        private String picUrl;
        private String url;

        public String getCtime() 
            return ctime;
        

        public void setCtime(String ctime) 
            this.ctime = ctime;
        

        public String getTitle() 
            return title;
        

        public void setTitle(String title) 
            this.title = title;
        

        public String getDescription() 
            return description;
        

        public void setDescription(String description) 
            this.description = description;
        

        public String getPicUrl() 
            return picUrl;
        

        public void setPicUrl(String picUrl) 
            this.picUrl = picUrl;
        

        public String getUrl() 
            return url;
        

        public void setUrl(String url) 
            this.url = url;
        
    

准备工作已做好,下面看Gson如何解析:

json,object互转

        String json = ...;
        Gson gson = new Gson();
        //json -> object
        NewsInfo newsInfo = gson.fromJson(json, NewsInfo.class);
        //object ->json
        gson.toJson(newsInfo);

数组的处理

Gson gson = new Gson();
int[] ints = 1, 2, 3, 4, 5;
String[] strings = "abc", "def", "ghi";

// Serialization
gson.toJson(ints);     // ==> [1,2,3,4,5]
gson.toJson(strings);  // ==> ["abc", "def", "ghi"]

// Deserialization
int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class); 
// ==> ints2 will be same as ints

泛型的处理

泛型的解析,需要通过Gson提供的TypeToken类,获取一个Type.

class Foo<T> 
  T value;

Gson gson = new Gson();
Foo<Bar> foo = new Foo<Bar>();
Type fooType = new TypeToken<Foo<Bar>>() .getType();
gson.toJson(foo,fooType); 
gson.fromJson(json, fooType);

null对象的处理

当一个对象的某个属性值为null时,Gson在生成json时会忽略掉这个属性。
Persion对象如下:

public class Person 
    public double height;
    public String name;
    public int age;

    public Person(double height, String name, int age) 
        this.height = height;
        this.name = name;
        this.age = age;
    

    //...get(),set()

比如:

        Gson gson = new Gson();
        Person person = new Person(1.72,null,10);
        Log.d(TAG,gson.toJson(person));// -->"age":10,"height":1.72

GsonBuilder

Gson对象有一个很强大的工厂类GsonBuilder,它可以在创建一个特定的Gson对象,用来制定转换规则。
若需要显示 null 对象:

        Gson gson = new GsonBuilder().serializeNulls().create();
        Person person = new Person(1.72,null,10);
        Log.d(TAG,gson.toJson(person));// -->"age":10,"height":1.72,"name":null

日期的处理

在Person类增加了下例字段:

    public Date birthday;

默认日期格式:

        Gson gson = new GsonBuilder().serializeNulls().create();
        Person person = new Person(1.72,null,10,new Date());
        Log.d(TAG,gson.toJson(person));// -->"age":10,"birthday":"Aug 15, 2016 19:42:52","height":1.72,"name":null

使用GsonBuilder格式化后的日志格式:

        Gson gson = new GsonBuilder().
                serializeNulls()
                .setDateFormat("yyyyMMdd")
                .create();
        Person person = new Person(1.72,null,10,new Date());
        Log.d(TAG,gson.toJson(person));// -->"age":10,"birthday":"20160815","height":1.72,"name":null

修改映射key名称

后端人员有时下发json也不安套路出牌,若后端下发给我们的是以下json:

"age":10,"birthday":"20160815","height":1.72,"person_name":null

但是我们移动端根本不需要这么详细的定义,还是想像之前一样使用name来表示姓名,那可不可以呢,当然可以,使用注解@SerializedName即可,这样Person修改为:

    public double height;
    @SerializedName("person_name")
    public String name;
    public int age;
    public Date birthday;

@SerializedName可以指定转换时,字段的key。

        Gson gson = new GsonBuilder().
                serializeNulls()
                .setDateFormat("yyyyMMdd")
                .create();
        String person_json = "\\"age\\":10,\\"birthday\\":\\"20160815\\",\\"height\\":1.72,\\"person_name\\":null";
        Person person = gson.fromJson(person_json, Person.class);
        Log.d(TAG,person.toString());// -->Personheight=1.72, name='null', age=10, birthday=20160815

忽略某些字段

当我们收到Person信息时,为了持久化数据,应该保存在数据库中,因此会增加一个id字段,Person字段修改如下:

    public double _id;//新增
    public double height;
    @SerializedName("person_name")
    public String name;
    public int age;
    public Date birthday;

当然,从后端下发下来的json不带_id字段也可以直接使用gson.fromJson()自动转换为Person对象,但是当我们将Person转换为json上传到后端时,如果不做处理,会自动的增加_id这个字段,如下:

        Gson gson = new GsonBuilder().
                serializeNulls()
                .setDateFormat("yyyyMMdd")
                .create();
        Person person = new Person(1,1.70,"raise",10, new Date());
        Log.d(TAG,gson.toJson(person));// -->"_id":1.0,"age":10,"birthday":"20160816","height":1.7,"person_name":"raise"

很明显,我们应该在生成json时,想办法踢掉这个_id字段,这是Gson提供了新的注解@Expose,用来显示哪些字段需要转换。
使用了新的注解后,记得在GsonBuilder时增加excludeFieldsWithoutExposeAnnotation()方法,转换的json就不带_id字段:
Person

    public double _id;
    @Expose //需要显示转换的字段
    public double height;
    @Expose
    @SerializedName("person_name")
    public String name;
    @Expose
    public int age;
    @Expose
    public Date birthday;
        Gson gson = new GsonBuilder()
                .serializeNulls()
                .excludeFieldsWithoutExposeAnnotation()//只转换带@Expose注解的字段
                .setDateFormat("yyyyMMdd")
                .create();
        Person person = new Person(1,1.70,"raise",10, new Date());
        Log.d(TAG,gson.toJson(person));// -->"age":10,"birthday":"20160816","height":1.7,"person_name":"raise"

参考资料:
http://www.studytrails.com/java/json/java-google-json-parse-json-to-java.jsp
http://blog.csdn.net/lk_blog/article/details/7685169

以上是关于Java_Gson json的学习的主要内容,如果未能解决你的问题,请参考以下文章

json 响应性决议

C++ 模板函数重载决议

公共场所人脸识别或全面被禁:欧洲议会决议,AI监管再收紧

撰写决议以完成今年的故事

sh Ubuntu通关屏决议

iOS开发底层之方法的慢速查找流程探索+方法动态决议上 - 10