[Android Getting Started to Project Combat -- 8.4] -- How to parse JSON format data

Table of contents

1. Preparation

Two, use JSONObject

3. Use GSON


        Compared with XML, the main advantage of JSON is that it is smaller in size and can save more traffic when transmitted on the network, but the disadvantage is that its semantics are poor and it does not look intuitive.

1. Preparation

        Or use the method in the previous article to read data on the server, you can first learn how to create a small server: https://blog.csdn.net/Tir_zhang/article/details/130462019?spm=1001.2014.3001.5501

        Before starting, create a new get_data.json file in the shared directory, and write the following 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"}]

Two, use JSONObject

        There are many ways to parse JSON data, you can use the official JSONObject, or you can use the Google open source library GSON.

        On the basis of the project in the previous article, continue to modify.

        Modify the MainActivity code as follows:

        First change the address of the HTTP request to your ip+json file, and call the parseJSONWithJSONObject method to parse the data after getting the data returned by the server.

        Since a JSON array is defined in the server, first pass the data returned by the server into a JSONArray object, and then traverse the object, and each element extracted from it is a JSONObject object, and each object contains id, name and version data, call the getString() method to retrieve the data.

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    TextView responseText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendRequest = (Button) findViewById(R.id.send_request);
        responseText = (TextView) findViewById(R.id.response_text);
        sendRequest.setOnClickListener(this);
    }

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

    private void sendRequestWithOkHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("http://192.168.0.114/get_data.json")
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    parseJSONWithJSONObject(responseData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private void parseJSONWithJSONObject(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 (Exception e) {
            e.printStackTrace();
        }
    }
}

The effect is as follows:

        Click the button to print the following log.

 

3. Use GSON

        GSON can automatically map a JSON-formatted string into an object, eliminating the need to manually write code for parsing.

        First open the build.gradle file and add the following to the dependencies closure:

implementation 'com.google.code.gson:gson:2.7'

        Create an App class and add fields as follows:

public class App {

    private String id;

    private String name;

    private String version;

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getVersion() {
        return version;
    }

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

}

        Modify the MainActivity code as follows:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    TextView responseText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendRequest = (Button) findViewById(R.id.send_request);
        responseText = (TextView) findViewById(R.id.response_text);
        sendRequest.setOnClickListener(this);
    }

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

    private void sendRequestWithOkHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("http://192.168.0.114/get_data.json")
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    parseJSONWithGSON(responseData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void parseJSONWithGSON(String jsonData) {
        Gson gson = new Gson();
        List<App> appList = gson.fromJson(jsonData, new TypeToken<List<App>>() {}.getType());
        for (App app : appList) {
            Log.d("MainActivity", "id is " + app.getId());
            Log.d("MainActivity", "name is " + app.getName());
            Log.d("MainActivity", "version is " + app.getVersion());
        }
    }

}

The effect is the same as the first method.

Guess you like

Origin blog.csdn.net/Tir_zhang/article/details/130470065