json data analysis and analysis in android

Keywords: JSON Google Attribute Java

1. Write in front

Through Guo Shen's code and instructions, together with the information reviewed in these two days, I learned a lot of json knowledge that I had not paid attention to before. The following points can be learned from this article.
A. JSON data form, there are generally three kinds
jsonObject: {key: value}, as long as it is json data in this form, it must be written as key-value. And if that's the case, no matter how complex, here's the figure( Guo Shen's Data If you use JSONObect parsing, the first step must be to turn string data into JSONObject, as follows

 JSONObject jsonObject = new JSONObject (string data obtained);

JSONArray:[], which can be divided into two types, [{}, {}, {}] and [","""",""", 111,true], regardless of which one of these arrays has at least one data, and if you want to use JSONArray to parse, no matter how complex the data structure, see the figure below.( Guo Shen's Data The first step is to use the following line of code.

 JSONArray jsonArray = new JSONArray(string type data);

That's what they have in common. The difference is that [{}, {}] this type of JSONArray, {} objects must be JSONObject, that is, must be written in the form of key-value.
B. Learned the difference between GSON parsing and JSONObject or JSONArray parsing. If GSON parsing wants to get data of a field in the whole json data (as shown below), it usually writes bean s well, then it can get objects outside the field directly through the method, and then it can get data through the object through get or. attribute. But JSONObject or JSONArray needs to peel the onion layer by layer to get the value of a field, and to get the outermost object, as well as layer by layer to plug data from the object inside to know what we want.
C. For a json data, we should write the fields we want in the bean exactly. If we are worried that the names of the fields do not match the names of the attributes defined by our java, we can solve it through Serialized Name in the GSON library, or we must write matches. As shown below, in the whole json data, I just want to get the value of these two fields. (The following example)

"lat":"28.197000","lon":"112.967000"

D. Find a good tool for viewing json data, HiJson 2.1.2_jdk64.exe, through which complex json data can be formatted. Of course, there are many such tools, and there are many online ones, if any, see the figure.

2. code

A. First of all, I said a lot of very definite words. Now I'll verify them.

Comparing these two, it is obvious that the above data is not json data. Put it into tool verification, see figure.
{"a":"bbb","b":2,"c":true,"d"}
{"a":"bbb","b":2,"c":true,"d":22.22}



And this kind of

["a",true,22.2,333,{"aa"}]and["a",true,22.2,333,{"aa":"ccc"}]

As mentioned above, as long as the {} must be in the form of key-value, otherwise it must not be json data, so the front is not json data, the back is, by the way, as mentioned earlier, as long as this [] form, if it is to be parsed with JSONArray, through the subscript value.


B. Write a small example, mainly for learning, JSONObject and JSONArray parse json data. The data sources are the two mentioned above.
Write links here
Write links here
I started by saying that for the first data, I need to parse it all out and display the names of the provinces as a list. For the second data, I want to get the value of two of the fields. See the picture.

The layout code is not pasted, it's very simple, two button s and a listview. And the interface I'm requesting here is okhttp3.
First, go to the tool to see the json data clearly.

According to the above data, it is more coincidental that the field key s in {} are the same, so they can be regarded as an object directly, and the whole array of this object. So I write this object as Province, the code is as follows, there's nothing to say, just field matching.

package guo.com.jsondataparse;

import com.google.gson.annotations.SerializedName;

/**
 * Created by ${GuoZhaoHui} on 2017/3/9.
 * email:guozhaohui628@gmail.com
 */

public class Province {

    @SerializedName("id")
    public int id;

    @SerializedName("name")
    public String name;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

Assuming that we have already obtained the json string from a network request, we first write a method to parse the data. As mentioned earlier, as long as the [] type is put in JSONArray first,

  JSONArray jsonArray = new JSONArray(response);

This becomes a json array, each element of which is a JSONObject, so I can iterate over the array.

for(int i=0;i<jsonArray.length();i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                Province province = new Province();
                province.setId(jsonObject.getInt("id"));
                province.setName(jsonObject.getString("name"));
                provinceList.add(province);
            }

Whenever a JSONObject approaches a field, it can get value through JOSNObject.getString("") or other means. Here I choose to save the value that the loop takes to the list.
The code is as follows:

 /**
     * Parsing json data into objects
     * @param response
     * @return
     */
    public List<Province> parseJsonProvince(String response){

        try {
            JSONArray jsonArray = new JSONArray(response);
            List<Province> provinceList = new ArrayList<>();
            for(int i=0;i<jsonArray.length();i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                Province province = new Province();
                province.setId(jsonObject.getInt("id"));
                province.setName(jsonObject.getString("name"));
                provinceList.add(province);
            }
            return provinceList;
        } catch (JSONException e) {
            e.printStackTrace();
        }
       return null;
    }

The next code is roughly to click the button, open the thread with okhttp3 request, get the response, parse it into a list with the method just now, traverse through a list loop, get the name attribute of the object in the list, and save it as a list. Switch to the main thread and load the adapter with listview. The code is as follows

 this.findViewById(R.id.bt).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        sendOkHttpRequest(URL1, new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {

                            }

                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                provinceList = parseJsonProvince(response.body().string());
                                for(Province province:provinceList){
                                    stringList.add(province.getName());
                                }
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, stringList);
                                        listView.setAdapter(arrayAdapter);
                                    }
                                });
                            }
                        });
                    }
                }.start();
            }
        });

Now for the second data parsing, I need to get the value of lat and lon fields in this data, as shown in the figure.

Thought: Because it's this form of {}, the first step must be

  JSONObject jsonObject = new JSONObject(response);

Then you can see that the value of this key corresponds to a [], so when you get the value through the key, the key must be written correctly, and you'd better copy it.

   JSONArray jsonArray =  jsonObject.getJSONArray("HeWeather");

Then look at the structure. We need two value s in the basic field, and basic is a field in the first element object in this array. So if we call basic an object, then these two fields are attributes. So first define the basic object.

package guo.com.jsondataparse;

import com.google.gson.annotations.SerializedName;

/**
 * Created by ${GuoZhaoHui} on 2017/3/10.
 * email:guozhaohui628@gmail.com
 */

public class Basic {

    @SerializedName("lat")
    public String lat;

    @SerializedName("lon")
    public String log;


    public String getLat() {
        return lat;
    }

    public void setLat(String lat) {
        this.lat = lat;
    }

    public String getLog() {
        return log;
    }

    public void setLog(String log) {
        this.log = log;
    }

    @Override
    public String toString() {
        return "Basic{" +
                "lat='" + lat + '\'' +
                ", log='" + log + '\'' +
                '}';
    }
}

There are many fields in basic in json data, but we don't need them, so write down two properties we need. Then I call the first element in the array [] weather, so that's what the weather class looks like.

package guo.com.jsondataparse;

import com.google.gson.annotations.SerializedName;

/**
 * Created by ${GuoZhaoHui} on 2017/3/10.
 * email:guozhaohui628@gmail.com
 */

public class Weather {

    @SerializedName("basic")
    public Basic basic;

}

Similarly, I'm just defining the attributes we need here.
Take the first element in this [] and look at json. We know it's a {}, so it's JSONObject.

   JSONObject  jsonWeather =  jsonArray.getJSONObject(0);

For this JSONObject, it's actually {basic": {lat":"28.222", "lon":"112.22"}, so similarly we get this value by key, and this value is also a JSONObject.

JSONObject jsonBasic =  jsonWeather.getJSONObject("basic");

At this point, the JSONObject is close to the field we need, so we get the value directly.

jsonBasic.getString("lat")
jsonBasic.getString("lon")    

The code is as follows:

 /**
     * Parse the lat and log fields in the weather json data and store the parsed data in the Basic object
     * @param response
     * @return
     */
    public Basic parseJsonBasic(String response){
        try {
            Basic basic = new Basic();
            JSONObject jsonObject = new JSONObject(response);
            JSONArray jsonArray =  jsonObject.getJSONArray("HeWeather");

            //GSON Analytical Method
//            String jsonWeather = jsonArray.getJSONObject(0).toString();
//            Weather weather = new Gson().fromJson(jsonWeather,Weather.class);
//            basic = weather.basic;

            JSONObject  jsonWeather =  jsonArray.getJSONObject(0);
            JSONObject jsonBasic =  jsonWeather.getJSONObject("basic");

            basic.setLat(jsonBasic.getString("lat"));
            basic.setLog(jsonBasic.getString("lon"));
            Log.i(TAG, basic.toString());
            return basic;
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

The next thought is the same as the first button click. First, click the button, open the thread inside to get the json data, parse the data through the method just now, switch to the main thread, and pop up a toast box.

    this.findViewById(R.id.bt2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        sendOkHttpRequest(URL2, new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {

                            }

                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                final Basic basic = parseJsonBasic(response.body().string());
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(MainActivity.this,"Longitude and latitude-->"+basic.toString(),Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        });
                    }
                }.start();
            }
        });

3. Source address

Source code

Posted by jaytux on Tue, 16 Apr 2019 03:21:34 -0700