码迷,mamicode.com
首页 > Web开发 > 详细

Gson解析json

时间:2017-04-24 21:07:14      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:解析   version   err   content   final   exce   dem   pack   nal   

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

标签:解析   version   err   content   final   exce   dem   pack   nal   

原文地址:http://www.cnblogs.com/itfenqing/p/6758798.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!