Android - Section 10 JSON explanation

Posted by getmizanur on Thu, 03 Mar 2022 20:26:56 +0100

1, Introduction to JSON

JSON(JavaScript Object Notation) is a lightweight data exchange format. It is based on a subset of JavaScript, which is easy for people to write and read, and easy for machine parsing. JSON adopts a text format completely independent of the language, but it also uses habits similar to the C language family (including C, C++, C#, Java, JavaScript, Perl, Python, etc.). These features make JSON an ideal data exchange language.

2, JSON represents an object

1.JSON format features 1

  • Start with "{" and end with "}". At the same time, it is a storage form of key value
  • key is usually a string
  • value can be a string, a number, or a boolean

Case 1:

json data:
{"name": "yaoyang",
"age":"20",
"sex":"boy"}

2. Parse the data in java



Core code:

package com.hnucm.a_test10;

import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONObject;

import java.awt.font.TextAttribute;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.*;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView=findViewById(R.id.tv);
        textView.setText("initialization");
        Thread thread = new Thread(){//Method 1
            @Override
            public void run() {
                super.run();
                //Child thread
                try {
                    //    URL url=new URL("http://www.baidu.com "); / / this is the domain name
                    URL url=new URL("https://www.fastmock.site/mock/2af8e2ac7371144c506cf0390b19e6c2/test/test2 "); / / get the server address
                    HttpURLConnection urlConnection= (HttpURLConnection) url.openConnection();//Both parties establish connection

                    urlConnection.setRequestMethod("GET");//Send request to server

                    //The data returned by the server is text, so the returned data is byte stream by default
                    InputStream inputStream=urlConnection.getInputStream(); //Byte stream
                    Reader reader=new InputStreamReader(inputStream); //Convert byte stream into character stream
                    BufferedReader bufferedReader=new BufferedReader(reader);//Characters are transferred into a buffer stream and can be read one line at a time

                    String result="";//initialization
                    String temp;
                    while ((temp=bufferedReader.readLine())!=null) {//When the data read by temp is empty, it ends
                        result += temp;//Splice temp together
                    }
                        Log.i("Main","result :"+result);
                        String finalResult=result;

                        Thread.sleep(2000);//The simulated network request takes a long time
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    //JSONObject jsonObject=new JSONObject(finalResult);
                                    //String s=jsonObject.getString("name");
                                    textView.setText(finalResult);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    inputStream.close();
                    reader.close();
                    bufferedReader.close();
                    //todo close flow
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        thread.start();

    }
}


Analysis format

Then get the key to return the corresponding value

Core code:

  //Parsing json object data
                                    JSONObject jsonObject=new JSONObject(finalResult);

                                    //Get results through key
                                    String name=jsonObject.getString("name");
                                    Integer age=jsonObject.getInt("age");
                                    String sex=jsonObject.getString("sex");
                                    Log.i("Main","Parsed data  name: "+name+"age: "+age+"sex: "+sex);

3, JSON format represents an array

1.JSON format features 2

  • If it is a bracket [], it is all value, and the values are separated by commas
    [value,value,...]
  • value can be string, number, boolean (must be of the same type)

Case 2:

json data: ["false", "true", "false"]

2. Parse the data in java

First pass the json data into the JSONArray, and then use the for loop to print the string one by one according to the position of the string in the array


Core code:

JSONArray jsonArray=new JSONArray(finalResult);
                                    for (int i=0; i<jsonArray.length();i++){
                                        String s = (String) jsonArray.get(i);
                                        Log.i("Main"," s:"+s);
                                    }

activity Code:

package com.hnucm.a_test10;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

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

import java.awt.font.TextAttribute;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.*;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView=findViewById(R.id.tv);
        textView.setText("initialization");
        Thread thread = new Thread(){//Method 1
            @Override
            public void run() {
                super.run();
                //Child thread
                try {
                    //    URL url=new URL("http://www.baidu.com "); / / this is the domain name
                    URL url=new URL("https://www.fastmock.site/mock/2af8e2ac7371144c506cf0390b19e6c2/test/test3 "); / / get the server address
                    HttpURLConnection urlConnection= (HttpURLConnection) url.openConnection();//Both parties establish connection

                    urlConnection.setRequestMethod("GET");//Send request to server

                    //The data returned by the server is text, so the returned data is byte stream by default
                    InputStream inputStream=urlConnection.getInputStream(); //Byte stream
                    Reader reader=new InputStreamReader(inputStream); //Convert byte stream into character stream
                    BufferedReader bufferedReader=new BufferedReader(reader);//Characters are transferred into a buffer stream and can be read one line at a time

                    String result="";//initialization
                    String temp;
                    while ((temp=bufferedReader.readLine())!=null) {//When the data read by temp is empty, it ends
                        result += temp;//Splice temp together
                    }
                        Log.i("Main","result :"+result);
                        String finalResult=result;

                        Thread.sleep(2000);//The simulated network request takes a long time
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    //Object parsing data json
                                    //JSONObject jsonObject=new JSONObject(finalResult);
                                    JSONArray jsonArray=new JSONArray(finalResult);
                                    for (int i=0; i<jsonArray.length();i++){
                                        String s = (String) jsonArray.get(i);
                                        Log.i("Main"," s:"+s);
                                    }
                                    //Get results through key
//                                    String name=jsonObject.getString("name");
//                                    Integer age=jsonObject.getInt("age");
//                                    String sex=jsonObject.getString("sex");
                                    textView.setText(finalResult);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    inputStream.close();
                    reader.close();
                    bufferedReader.close();
                    //todo close flow
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        thread.start();

    }
}

4, JSON nesting

1.JSON data nesting 1-json object + JSON object

Case 3:

json data:{
"age":20,
"name": "yaoyang",
"isboy":true,
"address":
{
"province": "Hunan province",
"city": "Changsha city"
}
}

java parsing:

Here's how to simply judge which method to use:
JSONObject is used if the outermost layer is braces {}, and JSONArray is used if the outermost layer is brackets []. The outermost layer of our group of data is braces, so we use JSONObject, and then parse the nested json objects in the parsed data


Core code:

JSONObject jsonObject=new JSONObject(finalResult);
                                    //Get results through key
                                    String name=jsonObject.getString("name");
                                    Integer age=jsonObject.getInt("age");
                                    Boolean isboy=jsonObject.getBoolean("isboy");
                                    
                                    JSONObject jsonObject1=jsonObject.getJSONObject("address");
                                    String province=jsonObject1.getString("province");
                                    String city=jsonObject1.getString("city");
                                    Log.i("Main","name: "+name+" age:"+age+" isboy:"+isboy+" province:"+province+" city:"+city);

2.JSON data nesting 2-json object + JSON array

The value value can be in the form of an array:

Case 4:

json data: {"grade": "level 18", "classname": "traditional Chinese medicine", "students": ["Zhang San", "Li Si", "Wang Wu"]}


Core code:

 JSONObject jsonObject=new JSONObject(finalResult);
                                    //Get results through key
                                    String name=jsonObject.getString("name");
                                    Integer age=jsonObject.getInt("age");
                                    Boolean isboy=jsonObject.getBoolean("isboy");
                                    Log.i("Main","name: "+name+" age:"+age+" isboy:"+isboy);

                                    JSONArray jsonArray=jsonObject.getJSONArray("province");
                                    for (int i=0; i<jsonArray.length();i++){
                                        String s = (String) jsonArray.get(i);
                                        Log.i("Main"," s:"+s);
                                   }

3.JSON data nesting 3-json object + JSON array + JSON object

Case 5:

json data: {"grade": "level 18", "classname": "Nursing College", "students": [{"id": "001", "age": 30, "name": "Zhang San", "IStudent": false}, {"id": "002", "age": 25, "name": "Li Si", "IStudent": true}, {"id": "003", "age": 26, "name": "Wang Wu", "IStudent": true}]}

It is recommended that you use online analysis tools to see the structure more obvious
Link: https://www.json.cn/.

5, Interface mock website

Here we recommend this website
Link: https://www.fastmock.site/#/.

Topics: Java Android Android Studio Apache