首页 > 代码库 > 解析Json数据

解析Json数据

一.json数据

[{"name":"free","version":"1.1","id":"1"},{"name":"love","version":"2.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 ){
            getJson();
        }
    }

    protected void getJson(){
        OkHttpClient http = new OkHttpClient.Builder()
                .connectTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();
        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 {
                parseJson(response.body().string());
            }
        });
    }

    protected void parseJson(String jsonStr){
        try{
            JSONArray jsonArray = new JSONArray(jsonStr);
            for(int i=0;i<jsonArray.length();i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String id = jsonObject.getString("id");
                String name = jsonObject.getString("name");
                String version = jsonObject.getString("version");
                Log.e("data", id + " | " + name + "|" + version);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

 

解析Json数据