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