Android parses data in JSON format

Parse JSON format data

Compared with XML, the main advantage of JSON is that it is smaller and can save more traffic when transmitted on the network. But the disadvantage is that it has poor semantics and does not look as intuitive as XML.

Before we start, we need to create a new get_data.json file in the Apache\htdocs directory, then edit this file and add the following JSON format content:

[{“id”:“5”,“version”:“5.5”,“name”:“Clash of Clans”},
{“id”:“6”,“version”:“7.0”,“name”:“Boom Beach”},
“id”:“7”,“version”:“3.5”,“name”:“Clash Royale”]

Visit the URL http://127.0.0.1/get_data.json, and the content shown in Figure 9.8 should appear.
Write picture description here
Let's start to parse these data in Android

Use JSONObject

 private void sendRequestWithOkHttp() {
    
    
        new Thread(new Runnable() {
    
    
            @Override
            public void run() {
    
    
                try {
    
    
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        //指定访问的服务器地址是电脑本机
                        .url("http://10.0.2.2/get_data.json")
                        .build();

                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    parseJSONWithJSNOObject(responseData);
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }
          }
        }).start();
    }
private void parseJSONWithJSNOObject(String jsonData){
    
    
	        try {
    
    
	            JSONArray jsonArray = new JSONArray(jsonData);
	            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.d("MainActivity","id is"+id);
	                Log.d("MainActivity","name is"+name);
	                Log.d("MainActivity","version is"+version);
	            }
	        } catch (JSONException e) {
    
    
	            e.printStackTrace();
	        }
	    }

Define a JSONArray array and pass in the data returned by the server; then traverse this array, and each element taken out is a JSONObject object, and each JSONObject object will contain fields, and the data can be taken out by the get method .

Two, GSON

Since it is an open source library, you need to import
compile'com.google.code.gson:gson:2.7' in the app/build.gradle file. The
GSON library is mainly to automatically map a string of JSON format into an object, so there is no need We are manually writing code for analysis.

For example, a piece of data in JSON format is as follows:

{“name”:”ads”, “age”:”12”} 

We can define a class and add the two fields of name and age. The JSON data can be automatically parsed into a Person object through the following code.

Gson gson = new Gson(); 
Person person = gson.fromJson(jsonData, Person.class);

If you are parsing a JSONS array, you can use the following methods:

List<Person> person = gson.fromJson(jsonData, new TypeToken<List<Person>>(){}.getType());

The basic syntax is like this. First, add an App class and add the three fields id, name, and version, as shown below:

public class JSONData {
    
    
    String id;
    String version;
    String name;

    public String getName() {
    
    
        return name;
    }

    public String getId() {
    
    
        return id;
    }

    public String getVersion() {
    
    
        return version;
    }

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

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

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

MainActivity.java

 private void sendHttpRequset() {
    
    
	        new Thread(new Runnable() {
    
    
	            @Override
	            public void run() {
    
    
	                try {
    
    
	                    OkHttpClient client = new OkHttpClient.Builder()
	                            .writeTimeout(60, TimeUnit.SECONDS)
	                            .readTimeout(60, TimeUnit.SECONDS)
	                            .connectTimeout(100, TimeUnit.SECONDS)
	                            .build();
	//                    OkHttpClient client = new OkHttpClient();
	                    Request requset = new Request.Builder()
	                            // 指定服务器的地址 - 10.0.2.2对于模拟器来说就是电脑本机的IP地址
	                            .url("http://10.0.2.2/get_data.json")
	                            .build();
	                    Response response = client.newCall(requset).execute();
	                    String responseData = response.body().string();
	                    parseJSONWithGSON(responseData);
	                } catch (Exception e) {
    
    
	                    e.printStackTrace();
	                }
	            }
	        }).start();
	    }

	 private void parseJSONWithGSON(String jsonData) {
    
    
	        Gson gson = new Gson();
	        List<JSONData> jsonDataList = gson.fromJson(jsonData, new TypeToken<List<JSONData>>(){
    
    }.getType());
	        for(JSONData data : jsonDataList){
    
    
	            Log.d(TAG, "id is:"+data.getId());
	            Log.d(TAG, "id is:"+data.getName());
	            Log.d(TAG, "id is:"+data.getVersion());
	        }
	    }

Guess you like

Origin blog.csdn.net/i_nclude/article/details/77985038