Gson解析json

Posted 罗夏

tags:

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

一.json数据

[{"name":"free","version":"1.1","id":"1"},{"name":"love","version":"2","id":"2"}]

 

二.关键代码

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    protected void myClick(View v){
        if( v.getId() == R.id.btn ){
            getJsonFromGson();
        }
    }

    protected void getJsonFromGson(){
        OkHttpClient http = new OkHttpClient();
        final Request request = new Request.Builder()
                .url("http://192.168.2.100:8001/a.php")
                .build();

        Call call = http.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                parseJsonFromGson(response.body().string());
            }
        });
    }

    private void parseJsonFromGson(String jsonStr){
        Gson gson = new Gson();
        List<App> appList = gson.fromJson(jsonStr,
                new TypeToken<List<App>>(){}.getType());

        for(App app:appList){
            Log.e("app", app.getId());
        }
    }
}

 

三.App类

package com.aotian.guo.gsondemo;

/**
 * Created by guo on 2017/4/24.
 */

public class App {
    private String name;
    private String version;
    private String id;

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getVersion() {
        return version;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setVersion(String version) {
        this.version = version;
    }
}

 

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

JSON 之GSON 解析

使用Gson解析Json

RecyclerView未显示已解析的GSON数据

使用 GSON 解析 JSON 数组

Gson解析比较复杂的json数据

Gson解析json