Gson基本使用


Gson的基本用法:

定义实体类

将JSON生成单个实体或列表实体集合


使用Gson解析JSONObject

使用Gson解析JSONArray

使用Gson将实体转为JSON数据


使用Gson时需要注意名字和JSON数据中的相同



简单来讲就是根据json的数据结构定义出相应的javabean --->

"new"出Gson的实例gson---->

gson.fromJson(jsonString,JavaBean.class) 即可.


JSON数据来源:https://api.douban.com/v2/book/1220562


Book.java

public class Book {

    private String title;

    private String publisher;

    private String summary;

    private ArrayList tags;

    public ArrayList getTags() {
        return tags;
    }

    public void setTags(ArrayList tags) {
        this.tags = 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;
    }

}


Tag.java

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.java

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() {
        StringRequest request = new StringRequest(url, new Response.Listener() {
            @Override
            public void onResponse(String s) {
                Log.d("MainActivity", s);
                dealData(s);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
        new Volley().newRequestQueue(getApplicationContext()).add(request);
    }

    private void dealData(String s) {
        Gson gson = new Gson();
        Book book = gson.fromJson(s, Book.class);
        Log.i("MainActivity", book.getTitle() + ":" + book.getPublisher() + ":" + book.getTags().size());
    }

}


此处涉及了Volley开源框架的基本使用

不熟悉可以移步至郭霖菊苣的博客:http://blog.csdn.net/guolin_blog/article/details/17482095/



Gson jar包下载地址:http://download.csdn.net/detail/duanliuchang/9667168


Volley jar包下载地址:http://download.csdn.net/detail/duanliuchang/9667177


源码:http://download.csdn.net/detail/duanliuchang/9667176






你可能感兴趣的:(Gson,JSON,Android,JSON解析)