Json解析开源框架--Gson 的基本使用

来源:互联网 发布:网络女主播谈恋爱 编辑:程序博客网 时间:2024/06/05 06:37

Gson 是google解析Json的一个开源框架,同类的框架fastJson,JackJson等等


根据一个GsonDemo工程来说明一下:

首先使用豆瓣图书的API接口:https://api.douban.com/v2/book/1220562

json数据如下:

{"rating":{"max":10,"numRaters":365,"average":"7.3","min":0},"subtitle":"","author":["[日] 片山恭一"],"pubdate":"2005-1","tags":[{"count":143,"name":"片山恭一","title":"片山恭一"},{"count":69,"name":"日本","title":"日本"},{"count":64,"name":"日本文学","title":"日本文学"},{"count":41,"name":"小说","title":"小说"},{"count":33,"name":"满月之夜白鲸现","title":"满月之夜白鲸现"},{"count":16,"name":"爱情","title":"爱情"},{"count":10,"name":"純愛","title":"純愛"},{"count":9,"name":"外国文学","title":"外国文学"}],"origin_title":"","image":"https://img3.doubanio.com\/mpic\/s1747553.jpg","binding":"平装","translator":["豫人"],"catalog":"\n      ","pages":"180","images":{"small":"https://img3.doubanio.com\/spic\/s1747553.jpg","large":"https://img3.doubanio.com\/lpic\/s1747553.jpg","medium":"https://img3.doubanio.com\/mpic\/s1747553.jpg"},"alt":"https:\/\/book.douban.com\/subject\/1220562\/","id":"1220562","publisher":"青岛出版社","isbn10":"7543632608","isbn13":"9787543632608","title":"满月之夜白鲸现","url":"https:\/\/api.douban.com\/v2\/book\/1220562","alt_title":"","author_intro":"","summary":"那一年,是听莫扎特、钓鲈鱼和家庭破裂的一年。说到家庭破裂,母亲怪自己当初没有找到好男人,父亲则认为当时是被狐狸精迷住了眼,失常的是母亲,但出问题的是父亲……。","price":"15.00元"}


添加Gson和Volley的gradle依赖:

dependencies {    compile fileTree(include: ['*.jar'], dir: 'libs')    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {        exclude group: 'com.android.support', module: 'support-annotations'    })    compile 'com.android.support:appcompat-v7:26.+'    compile 'com.android.support.constraint:constraint-layout:1.0.2'    compile 'com.mcxiaoke.volley:library:1.0.19'    testCompile 'junit:junit:4.12'compile '       compile 'com.google.code.gson:gson:2.8.2'}





添加网络权限:
<uses-permission android:name="android.permission.INTERNET"/>

创建实体类Book和Tag(标签类):
package com.example.dpl.gsondemo.bean;import java.util.ArrayList;/** * Created by dpl on 2017/10/3 0003. */public class Book {    private String title;    private String publisher;//出版社    private String summary;//简介    private ArrayList<Tag> tags;//标签数组    public String getTitle() {        return title;    }    public void setTitle(String title) {        this.title = title;    }    public String getPublisher() {        return publisher;    }    public void setPublisher(String publisher) {        this.publisher = publisher;    }    public String getSummary() {        return summary;    }    public void setSummary(String summary) {        this.summary = summary;    }    public ArrayList<Tag> getTags() {        return tags;    }    public void setTags(ArrayList<Tag> tags) {        this.tags = tags;    }}

package com.example.dpl.gsondemo.bean;/** * Created by dpl on 2017/10/3 0003. */public class Tag {//标签类    private String count;    private String name;    private String title;    public String getCount() {        return count;    }    public void setCount(String count) {        this.count = count;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getTitle() {        return title;    }    public void setTitle(String title) {        this.title = title;    }}

在MainActivity中实现Json数据的获取(使用日志的形式输出数据):
package com.example.dpl.gsondemo;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.StringRequest;import com.android.volley.toolbox.Volley;import com.example.dpl.gsondemo.bean.Book;import com.google.gson.Gson;public class MainActivity extends AppCompatActivity {    private String url="https://api.douban.com/v2/book/1220562";    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        getData();           }    private void getData() {        //这个方法构造出对象后,将请求对象添加到请求队列中,可以让我们发送一个        //get请求,在回调对象重写的方法中实现我们自己的业务。        StringRequest request=new StringRequest(url, new Response.Listener<String>() {            @Override            public void onResponse(String response) {                 Log.i("info",response);                 dealData(response);            }        }, new Response.ErrorListener() {            @Override            public void onErrorResponse(VolleyError error) {            }      });        new Volley().newRequestQueue(getApplicationContext()).add(request);//将请求对象添加到请求队列中    }    private void dealData(String result) {        Gson gson=new Gson();        Book book=gson.fromJson(result,Book.class);        //Gson提供了fromJson()方法来实现从Json相关对象到java实体的方法。        /*在日常应用中,我们一般都会碰到两种情况,转成单一实体对象和转换成对象列表或者其他结构。        先来看第一种:        比如json字符串为:[{“name”:”name0”,”age”:0}]        Person person = gson.fromJson(str, Person.class);        提供两个参数,分别是json字符串以及需要转换对象的类型。        第二种,转换成列表类型:        List<Person> ps = gson.fromJson(str, new TypeToken<List<Person>>(){}.getType());        可以看到上面的代码使用了TypeToken,它是gson提供的数据类型转换器,可以支持各种数据集合类型转换。        调试注意:        经过Gson解析成为map的数据,经常需要通过map.get(key)获取类型为Object的值,我们常需要将Object        进行强制转换,转换为我们需要的类型。这里注意,若我们想将整形数字1存入json串,经gson解析后,可能会        变成1.0,这样我们只能使用Double类对其进行强转,再使用Double类型的intValue()方法将其转为整形。*/        Log.i("info",book.getTitle()+":"+book.getPublisher()+"\n"+book.getTags().size()+":"+book.getSummary());    }}


运行效果:


原创粉丝点击