Ultra-detailed JSON parsing steps

Posted by Mr_Pancakes on Fri, 07 Jun 2019 21:36:45 +0200


AI Bible! Chinese Edition of Deep Learning Machine Learning-Data Mining System Training      Will you transform for AI?

[Topping] Ultra-detailed JSON parsing steps

2016-09-19 14:58 4561 people reading comment(1) Collection Report
Classification:
★★★ Android ★★★(229) [Android Foundation Stage] Android Network Programming (3) [Android Network Programming] Android Json parsing (7)

Introduction to JSON

  • JAVAScript Object Notation is a lightweight data exchange format
  • It has good readability and is easy to write quickly.
  • Mainstream technology in the industry provides a complete solution (somewhat similar to regular expressions, supported by most of today's languages)
  • JSON adopts a highly compatible text format and has similar behavior to C language system. Json.org
  • As one of the main data transmission formats in the network, JSON is widely used. It is not reluctant to say that the utilization rate of JSON reaches 99%.

Data types supported by JSON

If we want to learn how to use JSON parsing, we must have a deep understanding of the rules and principles of JSON parsing before we know one of its implementation principles.
Data in JSON exists as a key-value pair
("key": "value") The type of median can be any of the following data types:
1. Numbers (integers or floating-point numbers)
2. Logical values (true or false)
3. Strings (in double quotes)
4. Arrays (in square brackets)
5. Functions
6. Objects (in brackets)
7. null

JSON grammar rules

JSON's grammatical rules are very simple, that is, to use
Braces'{}',
The middle brackets'[]',
Commas',',
Colon':',
Double quotation marks'"."

Data type:
Nested objects, arrays, strings, numbers, Boolean values, or null values.

Only three of our JSON parsing scenarios occur.
1. Analytical bracket type
2. [] Resolution is a bracket type
3. Actually, there are only two kinds. The third one is the combination of 1 and 2, i.e. "[name],'Li Shuhao','hobby': ['programming','Electronic competition','sleeping']]." Then, let's look at these three types and analyze them separately.

JSON Basic Grammar and Legend

  • Object (Object Type)
    • It is represented by {} containing a series of disorderly key-value pairs, in which the key and Value are separated by colons and each key-value is separated by commas.
    • For example:
  • Array (array type)
    • Use [] to contain all elements, each separated by commas, and elements can be arbitrary values
    • For example:
  • Combinatorial Form

JSON Data Parsing

  • Two rules that must be mastered in JSON parsing:

    • 1. If you see {} -> use JSONObject
    • 2. If you see [] -> parse using JSONArray
  • After mastering the data type and basic grammar of JSON, we will parse the various grammar types of JSON in detail (pay attention to the use of two rules, master JSON parsing is the same thing)

Analysis of Pure Object {}:

import org.json.JSONException;
import org.json.JSONObject;

/**
 * JSON-->Analysis of Pure Object
 * 
 * Note: We need third-party jar packages to support JSON parsing in eclipse
 * @author sKy°
 * @date 2016-5-8
 * @version 1.0
 */
public class Json01 {
    public static void main(String[] args) {
//      Edit a data object we want to parse
//     According to the official definition of JSON, key, add ", value, if it is a string, add", other do not add.
        String json="{'name':'Li Shuhao','age':24}";

        try {
//          Create JSON parsing objects (two rules: use JSONObject in braces, pay attention to incoming data objects)
            JSONObject obj = new JSONObject(json);
//          obj. There are various types of data that can be selected according to the object.
            String name = obj.getString("name");
//          Similarly, the age here is of type Int, and we parse it with the corresponding type.
            int age = obj.getInt("age");
//          Finally output to console
            System.out.println(name+"<--->"+age);

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}

The parsing {} of pure arrays (Array): ____________

import org.json.JSONArray;
import org.json.JSONException;

/**
 * Analysis of Pure Array
 * @author sKy°
 * @date 2016-5-8
 * @version 1.0
 */
public class Json02 {
    public static void main(String[] args) {
//      Edit a data object we want to parse
        String json="['Tianjin Cold','Beijing Warm','Tokyo fever','Nanjing Liang']";

        try {
//          Create JSON parsing objects (two rules: use JSONArray in brackets, pay attention to incoming data objects)
            JSONArray jArray = new JSONArray(json);
//          Get the length of the array
            int length = jArray.length();
//          Recall how arrays are valued? - > for loop traversal array - - > get the value
            for (int i = 0; i < length; i++) {
//              Use this type of get method to get the value according to the parsed data type and print it out.
                String string = jArray.getString(i);
                System.out.print(string+",");
            }

        } catch (JSONException e) {
            // TODO: handle exception
        }


    }
}

Analysis of Combination Types (1):

  • Examples: String json="{name:'Li Shuhao','girlFriend': {name:'high circle','age': 18}";
  • Analysis: First, we parse the object in outer brackets, and then, through girlf Friend, we get the corresponding object in Inner brackets. So here we need to create a class, encapsulate the corresponding data fields, and get the corresponding values according to setName, setAge.
/**
 * Create a Person to receive parsed data and encapsulate corresponding fields
 * @author sKy°
 * @date 2016-5-8
 * @version 1.0
 */
public class Person {
//    Analyse the object we want to parse, and create the corresponding attribute value according to the attribute value of the parsed object.
//    According to the object we want to parse, the two attributes are 1.name(String type) and 2. girlFrien (class type, which means that we need to nest a class in the class (creating a class part class is also possible).

//   Encapsulation field
    private String name;
    private GirlFriend girlFriend;  //Class type
//   setter getter method
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public GirlFriend getGirlFriend() {
        return girlFriend;
    }
    public void setGirlFriend(GirlFriend girlFriend) {
        this.girlFriend = girlFriend;
    }

//   toString method for console output
    @Override
    public String toString() {
        return "Person [name=" + name + ", girlFriend=" + girlFriend + "]";
    }

}

// For our convenience, here we create a GirlFriend class directly below.
class GirlFriend{
//   Create corresponding values based on object attribute values
    private String name;
    private int age;
//   setter getter method
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
//   toString method for console output
    @Override
    public String toString() {
        return "GirlFriend [name=" + name + ", age=" + age + "]";
    }



}

Start analysing:
import org.json.JSONException;
import org.json.JSONObject;





/**
 * Analysis of Composite Data Types - > Object Nested Object Types
 * @author sKy°
 * @date 2016-5-8
 * @version 1.0
 */
public class Json03 {
    public static void main(String[] args) {
//      Edit a data object we want to parse
//      Analysis: We should first parse the large objects outside, and then get the corresponding contained objects through girlfFriend.
//      So here we need to create a class, encapsulate the corresponding data fields, and get the corresponding values according to setName, setAge.

        String json="{'name':'Li Shuhao','girlFriend':{'name':'High circle','age':18}}";
        try {
//          1. Create JSON parsing objects (two rules: use JSONObject in brackets, pay attention to the incoming data objects)
            JSONObject jObj = new JSONObject(json);
//          2. Instantiate the Person object to get the corresponding value - > Here is the thinking of getting the name value of the outer bracket {} and how to get the inside {}?
            Person per=new Person();
            String name = jObj.getString("name");
            per.setName(name);
//          3. Analysis: The inner {} is nested in the outer bracket class, so the object we parse is to get the inner bracket value through the outer bracket, pay attention to it.
            //Get the girlFriend in the corresponding braces, get the name value, and assign it to the girlFriend object
            GirlFriend girlFriend=new GirlFriend();
            JSONObject jObj1 = jObj.getJSONObject("girlFriend");
            String gfName = jObj1.getString("name");
            girlFriend.setName(gfName);
//          Get the age value and assign it
            int gfAge = jObj1.getInt("age");
            girlFriend.setAge(gfAge);
//          The value of girlFriend is assigned to Person by set for the output of toString, otherwise it is empty.
            per.setGirlFriend(girlFriend);
//          output
            System.out.println(per);
    }catch (JSONException e) {
        e.printStackTrace();
    }
    }
}


Summary: [{}, {}] > train of thought: the first step is to see brackets: JSONObject to solve, create the corresponding value of the attributes; the second step is to see brackets: JSONArray to parse the corresponding value of the attributes created within the corresponding; the third step is {} in brackets, another JSONObject. The idea is roughly the same. It is emphasized that the attribute value set Xxx getXxx must be consistent with the name of the value obtained, otherwise it will be wrong!!

Analysis of Combination Types (2):

Now let's parse a slightly more complex JSON data
The data to be analyzed are as follows:

{
    'desc': 'OK',
    'status': 1000,
    'data': {
        'wendu': '20',
        'ganmao': 'Relative to today's dramatic cooling, susceptible to colds, please pay attention to the appropriate increase in clothing, strengthen self-protection to avoid colds.',
        'forecast': [
            {
                'fengxiang': 'North wind',
                'fengli': '3-4 level',
                'high': 'High temperature 27℃',
                'type': 'Moderate rain',
                'low': 'Low temperature 19℃',
                'date': '6 Sunday, Friday'
            },
            {
                'fengxiang': 'North wind',
                'fengli': 'Breeze level',
                'high': 'High temperature 23℃',
                'type': 'Heavy rain',
                'low': 'Low temperature 17℃',
                'date': '7 Sunday and Saturday'
            },
            {
                'fengxiang': 'North wind',
                'fengli': 'Breeze level',
                'high': 'High temperature 26℃',
                'type': 'Light rain',
                'low': 'Low temperature 17℃',
                'date': '8 Sunday and Sunday'
            },
            {
                'fengxiang': 'Southerly wind',
                'fengli': 'Breeze level',
                'high': 'High temperature 27℃',
                'type': 'Cloudy',
                'low': 'Low temperature 15℃',
                'date': '9 Sunday, Monday'
            },
            {
                'fengxiang': 'Southerly wind',
                'fengli': 'Breeze level',
                'high': 'High temperature 29℃',
                'type': 'Cloudy',
                'low': 'Low temperature 16℃',
                'date': '10 Sunday, Tuesday'
            }
        ],
        'yesterday': {
            'fl': 'Breeze',
            'fx': 'North wind',
            'high': 'High temperature 33℃',
            'type': 'Yin',
            'low': 'Low temperature 22℃',
            'date': '5 Sunday, Thursday'
        },
        'aqi': '58',
        'city': 'Chengdu'
    }
}

Because the data is slightly larger, it is not convenient for us to see. Here we provide you with a JSON online parsing tool. http://json.phpddt.com/ This is JSON on-line highlight analysis, which can help us to analyse. Here are the pictures I parsed on the web page. You can think about the next steps (remember two rules)

Analysis:

First: the first bracket (JSONObject) "desc":"status":"data"
Two: There is a bracket (JSONObject) "wendu", "20", "ganmao", "forecast", "yesterday", "aqi", "city":"
Three: There are two objects in the second bracket: 1. Array (JSONArray) 2. Object (JSONObject)
And inside the array, there is an object {} of the array. This requires us to create the corresponding attribute values carefully when parsing. JSON parsing is not difficult, and the painful part is now mentioned in the creation of classes, as long as it is careful and super simple!

Start encapsulating fields:

import java.util.List;

/**
 * Encapsulation of corresponding fields
 * @author sKy°
 * @date 2016-5-6
 * @version 1.0
 */
public class Weather {
//  Outside bracketed fields encapsulate setter getter to String
    public String desc;
    public int status;
    public Data data;
    @Override
    public String toString() {
        return "Weather [desc=" + desc + ", status=" + status + ", data="
                + data + "]";
    }


}

class Data{
//  The fields in braces encapsulate setter getter to String 
//  This class contains arrays and objects, which need to be encapsulated together.
    public String wendu;
    public String ganmao;
    public List<Forecast> forecast;
    public Yesterday yesterday;
    public String aqi;
    public String city;
    @Override
    public String toString() {
        return "Data [wendu=" + wendu + ", ganmao=" + ganmao + ", forecast="
                + forecast + ", yesterday=" + yesterday + ", aqi=" + aqi
                + ", city=" + city + "]";
    }


}

class Forecast{
//  Encapsulation of bracket type fields in arrays
    public String fengxiang;
    public String fengli;
    public String high;
    public String type; 
    public String low;
    public String date;
    @Override
    public String toString() {
        return "Forecast [fengxiang=" + fengxiang + ", fengli=" + fengli
                + ", high=" + high + ", type=" + type + ", low=" + low
                + ", date=" + date + "]";
    }


}
class Yesterday{
//   Finally {} field encapsulation
    public String fl;
    public String fx;
    public String high;
    public String type;
    public String low;
    public String date;
    @Override
    public String toString() {
        return "Yesterday [fl=" + fl + ", fx=" + fx + ", high=" + high
                + ", type=" + type + ", low=" + low + ", date=" + date + "]";
    }

}

Start analysing:

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;




/**
 * Analysis of Combination Type 2
 * @author sKy°
 * @date 2016-5-6
 * @version 1.0
 */
public class Test01 {
    public static void main(String[] args) throws Exception {

         //Objects to parse
        String json="{ 'desc': 'OK', 'status': 1000, 'data': { 'wendu': '20', 'ganmao': 'Relative to today's dramatic cooling, susceptible to colds, please pay attention to the appropriate increase in clothing, strengthen self-protection to avoid colds.', 'forecast': [ { 'fengxiang': 'North wind', 'fengli': '3-4 level', 'high': 'High temperature 27℃', 'type': 'Moderate rain', 'low': 'Low temperature 19℃', 'date': '6 Sunday, Friday' }, { 'fengxiang': 'North wind', 'fengli': 'Breeze level', 'high': 'High temperature 23℃', 'type': 'Heavy rain', 'low': 'Low temperature 17℃', 'date': '7 Sunday and Saturday' }, { 'fengxiang': 'North wind', 'fengli': 'Breeze level', 'high': 'High temperature 26℃', 'type': 'Light rain', 'low': 'Low temperature 17℃', 'date': '8 Sunday and Sunday' }, { 'fengxiang': 'Southerly wind', 'fengli': 'Breeze level', 'high': 'High temperature 27℃', 'type': 'Cloudy', 'low': 'Low temperature 15℃', 'date': '9 Sunday, Monday' }, { 'fengxiang': 'Southerly wind', 'fengli': 'Breeze level', 'high': 'High temperature 29℃', 'type': 'Cloudy', 'low': 'Low temperature 16℃', 'date': '10 Sunday, Tuesday' } ], 'yesterday': { 'fl': 'Breeze', 'fx': 'North wind', 'high': 'High temperature 33℃', 'type': 'Yin', 'low': 'Low temperature 22℃', 'date': '5 Sunday, Thursday' }, 'aqi': '58', 'city': 'Chengdu' } }";

        Weather wea=new Weather();
//      The first thing you see is a {} so parse with JSON Object
//      Get external Weather
        JSONObject obj = new JSONObject(json);
        String desc = obj.getString("desc");
        int status = obj.getInt("status");
        wea.status=status;
        wea.desc=desc;

//      Get data from internal Data
        JSONObject obj1 = obj.getJSONObject("data");
        Data data=new Data();
        data.wendu=obj1.getString("wendu");
        data.ganmao=obj1.getString("ganmao");
        data.aqi=obj1.getString("aqi");
        data.city=obj1.getString("city");
        wea.data=data;
        List<Forecast> forecasts=new ArrayList<>();

//      Get the forecast array
        JSONArray jArr = obj1.getJSONArray("forecast");
        for (int i = 0; i < jArr.length(); i++) {
            JSONObject obj2 = jArr.getJSONObject(i);
            Forecast forecast=new Forecast();
            forecast.date=obj2.getString("date");
            forecast.fengxiang=obj2.getString("fengxiang");
            forecast.high=obj2.getString("high");
            forecast.low=obj2.getString("low");
            forecast.fengli=obj2.getString("fengli");
            forecast.type=obj2.getString("type");
            forecasts.add(forecast);
        }
        data.forecast=forecasts;
        JSONObject obj3 = obj1.getJSONObject("yesterday");
        Yesterday yesterday=new Yesterday();
        yesterday.fl=obj3.getString("fl");
        yesterday.fx=obj3.getString("fx");
        yesterday.high=obj3.getString("high");
        yesterday.type=obj3.getString("type");
        yesterday.low=obj3.getString("low");
        yesterday.date=obj3.getString("date");
        data.yesterday=yesterday;

//      Output field
        System.out.println(wea);
    }

Analytical results:

Concluding remarks: A superficial view of JSON's analysis of individuals.
1. First, an analysis of JSON data
2. Secondly, master some skills of JSON (two rules - object JSONObject, array JSONArray)
3. Then encapsulate the corresponding fields of the corresponding attribute values and establish corresponding classes (careful analysis, clear thinking, the line of the program needs patience and can not be impetuous)
4. Then there should be clear thinking in the analysis.

(The above is just a preliminary JSON parsing, but the general idea of JSON parsing is the same, followed by http application, no more than the downloaded file into JSON object, the same is true of the latter parsing ideas, write bad place everyone includes! If you have any questions, please leave a message!

Topics: JSON Attribute Android network