Android——JSONObject解析JSON数据

添加jar包

implementation 'com.squareup.okhttp3:okhttp:3.4.1'

闭包里申请网络权限


布局文件中就一个Button,此处不再阐述,解析的XML数据将以日志方式体现
MainActivity.java代码如下:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button SendRequest;

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

        SendRequest = (Button) findViewById(R.id.SendRequest);
        SendRequest.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.SendRequest){
            SendRequestToHttp();
        }

    }
    private void SendRequestToHttp(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder().url("http://192.168.0.60:8888/data.json").build();
                    Response response = client.newCall(request).execute();
                    String ResponseData = response.body().string();
                    JSONParseWithJsonObject(ResponseData);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private void JSONParseWithJsonObject(String Data){
        try {
            //将服务器返回的数据放入一个json数组内
            JSONArray array = new JSONArray(Data);
            for (int i = 0; i < array.length(); i++) {
                //jsonObject对象都包含id,name,version
                JSONObject jsonObject = array.getJSONObject(i);
                String id = jsonObject.getString("id");
                String name = jsonObject.getString("name");
                String version = jsonObject.getString("version");
                Log.d("ID = ",id);
                Log.d("name = ",name);
                Log.d("version = ",version);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}

你可能感兴趣的:(Android,Studio,json,android,java,android,studio)