JSON data study notes

JSON

The concept of JSON

  • JSON :javascript object notation
  • JSON is a syntax for storing and exchanging textual information, similar to XML. But json is smaller, faster and easier to parse than xml.
  • JSON is language independent: JSON uses Javascript syntax to describe data objects, but JSON is still language and platform independent. JSON parsers and JSON libraries support many different programming languages. Currently, many dynamic (PHP, JSP, .NET) programming languages ​​support JSON.
  • JSON is suitable for data interaction scenarios, such as the data interaction between the foreground and the background of a website.

Syntax of JSON

  1. The syntax of json is a subset of the syntax of Javascript.
    • Data is in name/value pairs
    • Data is separated by commas ,
    • Use slashes * * to escape characters
    • Braces { } hold the object
    • Brackets [] save the array, the array can contain multiple objects
  2. json data structure
    • 1. The object saved by curly braces { } is an unordered collection of name/value pairs. An object starts with an opening bracket { and ends with a closing bracket } . Each "key" is followed by a colon : , and name/value pairs are separated by commas , .
    • **Array: **The array stored in brackets [] is an ordered collection of values. An array ends with a left square bracket [ beginning, a right square bracket ] , and values ​​are separated by commas .

json writing format

The writing format of JSON data is:

key : value

JSON values ​​can be:

  • number (integer or float)
  • string (in double quotes)
  • logical value (true or false)
  • array (in square brackets)
  • object (in braces)
  • null

JSON object: JSON object is written in braces {} . The following is a json object.

 {
    
    
    "id": 41,
    "name": "重庆",
    "weather_id": "CN101040100"
 }

JSON array: JSON array is written in square brackets [] , and the array can contain multiple objects.

In the following example the object city is an array containing four objects.

{
    
    
 "city":[
         {
    
    "id": 41, "name": "重庆", "weather_id": "CN101040100"},
 		 {
    
    "id": 42, "name": "永川", "weather_id": "CN101040200"},
 		 {
    
    "id": 43, "name": "合川", "weather_id": "CN101040300"},
		 {
    
    "id": 44, "name": "南川", "weather_id": "CN101040400"}
      ]
}

JSON formatter

The method of parsing json data in Android

1.JsonObject

Use JSONObject to parse JSON data, which is the most basic data parsing method in Android. Google's official method for parsing json data.

The Json parsing class provided in Android

  • JSONObject: Json object, which can complete the mutual conversion between Json string and Java object
  • JSONArray: Json array, which can convert between Json strings and Java collections or objects
  • JSONStringer: Json text construction class, this class can help create JSON text quickly and conveniently, each JSONStringer entity can only create one JSON text
  • JSONTokener: Json parsing class
  • JSONException: Json exception

The following code examples are used for analysis:

1. Use the JSONArray class to parse the main logic code of JSON data

[{
    
    "name":"LiLi","score":"95"},{
    
    "name":"LiLei","score":"99"},{
    
    "name":"王明","score":"100"},{
    
    "name":"LiLei","score":"89"}]

Note: Because "" means to declare a string, what we initialized is a String string, so we need to use \ to escape " in the object , otherwise it will cause the problem that the String string ends early.

public static void JsonEg(){
    
    
    String json="[{\"name\":\"LiLi\",\"score\":\"95\"},{\"name\":\"LiLei\",\"score\":\"99\"},{\"name\":\"王明\",\"score\":\"100\"},{\"name\":\"LiLei\",\"score\":\"89\"}]";
    try {
    
    
        JSONArray jsonArray=new JSONArray(json);
        for (int i=0;i<jsonArray.length();i++){
    
    
            JSONObject object=jsonArray.getJSONObject(i);
            String name=object.optString("name");
            int score=object.optInt("score");
            Log.d("TAG", "JsonEg: "+name+"_______"+score);
        }
    } catch (Exception e) {
    
    
        e.printStackTrace();
    }
}

insert image description here

The difference between optString and getString :
optString("key") returns "" if it is empty, and no exception is reported. Advantages: It will not make the program wrong for the key value.
If getString("key") is empty, it will return a null pointer exception.

2.jsonObject object analysis

{
    
    
    "user":{
    
    
        "name":"alex",
        "age":"18",
        "isMan":true
    }
}
public class OrgJSONTest {
    
     
	public static String json = "{\"user\":{\"name\":\"alex\",\"age\":\"18\",\"isMan\":true}}";
        public static void main(String[] args) {
    
    
            try {
    
    
                JSONObject obj = new JSONObject(json);//最外层的JSONObject对象
                JSONObject user = obj.getJSONObject("user");//通过user字段获取其所包含的JSONObject对象
                String name = user.getString("name");//通过name字段获取其所包含的字符串
                System.out.println(name);
            } catch (JSONException e) {
    
    
                e.printStackTrace();
            }
        }

Print result:

alex

3. Create a json data, parse and print the json data.

{
    
    
    "cat":"it",
    "languages":[
        {
    
    "id":1,"ide":"Eclipse","name":"Java"},
        {
    
    "id":2,"ide":"XCode","name":"Swift"},
        {
    
    "id":3,"ide":"Visual Studio","name":"C#"}
    ]
}

Specific code:

activity_main.xml code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.oak.d4_json.MainActivity">
 
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="创建"
        android:id="@+id/bt_create"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="读取"
        android:id="@+id/bt_read"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/tv"/>
</LinearLayout>

MainActivity.java code:

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
    
    
    private Button bt_create;//声明创建按钮组件变量
    private Button bt_read;//声明读取按钮组件变量
    private File file;//声明一个文件对象
    private TextView tv;//声明TextView组件变量
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bt_create = (Button) findViewById(R.id.bt_create);//获取到创建按钮组件
        bt_read = (Button) findViewById(R.id.bt_read);//获取到读取按钮组件
        tv = (TextView) findViewById(R.id.tv);//获取到TextView组件

        file = new File(getFilesDir(),"Test.json");//获取到应用在内部的私有文件夹下对应的Test.json文件
        bt_create.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View view) {
    
    
                try {
    
    
                    JSONObject root = new JSONObject();//实例一个JSONObject对象
                    root.put("cat","it");//对其添加一个数据

                    JSONArray languages = new JSONArray();//实例一个JSON数组
                    JSONObject lan1 = new JSONObject();//实例一个lan1的JSON对象
                    lan1.put("id",1);//对lan1对象添加数据
                    lan1.put("ide","Eclipse");//对lan1对象添加数据
                    lan1.put("name","Java");//对lan1对象添加数据
                    JSONObject lan2 = new JSONObject();//实例一个lan2的JSON对象
                    lan2.put("id",2);//对lan2对象添加数据
                    lan2.put("ide","XCode");//对lan2对象添加数据
                    lan2.put("name","Swift");//对lan2对象添加数据
                    JSONObject lan3 = new JSONObject();//实例一个lan3的JSON对象
                    lan3.put("id",3);//对lan3对象添加数据
                    lan3.put("ide","Visual Studio");//对lan3对象添加数据
                    lan3.put("name","C#");//对lan3对象添加数据
                    languages.put(0,lan1);//将lan1对象添加到JSON数组中去,角标为0
                    languages.put(1,lan2);//将lan2对象添加到JSON数组中去,角标为1
                    languages.put(2,lan3);//将lan3对象添加到JSON数组中去,角标为2

                    root.put("languages",languages);//然后将JSON数组添加到名为root的JSON对象中去

                    FileOutputStream fos = new FileOutputStream(file);//创建一个文件输出流
                    fos.write(root.toString().getBytes());//将生成的JSON数据写出
                    fos.close();//关闭输出流
                    Toast.makeText(getApplicationContext(),"创建成功!",Toast.LENGTH_SHORT).show();
                } catch (JSONException | IOException e) {
    
    
                    e.printStackTrace();
                }
            }
        });
        bt_read.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View view) {
    
    
                try {
    
    
                    FileInputStream fis = new FileInputStream(file);//获取一个文件输入流
                    InputStreamReader isr = new InputStreamReader(fis);//读取文件内容
                    BufferedReader bf = new BufferedReader(isr);//将字符流放入缓存中
                    String line;//定义一个用来临时保存数据的变量
                    StringBuilder sb = new StringBuilder();//实例化一个字符串序列化
                    while((line = bf.readLine()) != null){
    
    
                        sb.append(line);//将数据添加到字符串序列化中
                    }
                    //关闭流
                    fis.close();
                    isr.close();
                    bf.close();
                    JSONObject root = new JSONObject(sb.toString());//用JSONObject进行解析
                    String cat = root.getString("cat");//获取字符串类型的键值对
                    tv.append("cat"+"="+cat+"\n");//显示数据
                    tv.append("---------------"+"\n");//分割线
                    JSONArray array = root.getJSONArray("languages");//获取JSON数据中的数组数据
                    for (int i=0; i<array.length(); i++){
    
    
                        JSONObject object = array.getJSONObject(i);//遍历得到数组中的各个对象
                        int id = object.getInt("id");//获取第一个值
                        String ide = object.getString("ide");//获取第二个值
                        String name = object.getString("name");//获取第三个值
                        tv.append("id"+"="+id+"\n");//显示数据
                        tv.append("ide"+"="+ide+"\n");//显示数据
                        tv.append("name"+"="+name+"\n");//显示数据
                        tv.append("---------------"+"\n");//分割线
                    }
                } catch (IOException | JSONException e) {
    
    
                    e.printStackTrace();
                }
            }
        });
    }
}

2.GSON

​ Use Gson to get data in Json

{
    
    
	"data": {
    
    
		"stuID": 1111,
		"passwd": "admin",
		"name": "admin",
		"email": "[email protected]",
		"authority": "admin",
		"state": 0
	},
	"error": 0
}

Create a FullBackResponse.javafile for processing data.
The general idea is that non- nested data uses gettingand settingmethods to assign values ​​to variables,
nested data is assigned to an entity class through the above method, and the corresponding variable value is obtained in the entity class.

public class FullBackResponse {
    
    
    private dataBean data;
    private int error;

	// Json 内嵌套的实体类
    public static class dataBean{
    
    
        private int stuID;
        private String passwd;
        private String name;
        private String email;
        private String authority;
        private int state;

        public int getStuID() {
    
    
            return stuID;
        }
        public void setStuID(int stuID) {
    
    
            this.stuID = stuID;
        }

        public String getPasswd() {
    
    
            return passwd;
        }
        public void setPasswd(String passwd) {
    
    
            this.passwd = passwd;
        }

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

        public String getEmail() {
    
    
            return email;
        }
        public void setEmail(String email) {
    
    
            this.email = email;
        }

        public String getAuthority() {
    
    
            return authority;
        }
        public void setAuthority(String authority) {
    
    
            this.authority = authority;
        }

        public int getState() {
    
    
            return state;
        }
        public void setState(int state) {
    
    
            this.state = state;
        }
    }

    public dataBean getData() {
    
    
        return data;
    }
    public void setData(dataBean data) {
    
    
         this.data = data;
    }

    public int getError() {
    
    
        return error;
    }
    public void setError(int error) {
    
    
        this.error = error;
    }
}

// res 是 String 类型的 Json 数据
FullBackResponse fullBackResponse = gson.fromJson(res, FullBackResponse.class);

// 将数据赋值给变量
// 这两个是 Json 内嵌套的 实体类 里的数据
int LoginResponse_stuID = fullBackResponse.getData().getStuID();
String LoginResponse_passwd = fullBackResponse.getData().getPasswd()// 着个不是嵌套的数据
int LoginResponse_error = fullBackResponse.getError();

Android JSON data analysis
https://blog.csdn.net/qq_53958979/article/details/125086028
Android Java uses Gson to get data in Json (including nested data)
https://blog.csdn.net/qq_17790209/article /details/126950237

Guess you like

Origin blog.csdn.net/qq_43867812/article/details/129722709