[Java knowledge point sorting] JSON

Optimize concatenated strings

String

  • Is a composite type, equivalent to an array of char

  • It is a final class, that is, it does not support inheritance

    public final class String {
          
          
        private final char value[];
    。。。。
    }
    
    • Low-level analysis : When the String string is concatenated, a new char array will be created.

      **That is: **Every time you operate on a String object, you need to create a new object and copy the data one by one to the new space.

    • **Disadvantages:** It takes up more space and is slower.

how to solve this problem?

  • Use StringBuffer, which is also a String object, but can be modified multiple times.

StringBuffer——Synchronized with synchronization block, suitable for multi-threaded use, slower speed

StringBuilder—— The newly added equivalence class does not have a synchronization block, so it is used by a single thread and the speed is faster

3. Interview questions: the difference between the three

1. String is a string constant. Once the object is created, it cannot be changed. This leads to the fact that there is no required object in the string constant pool. Every time a String object is operated, a new String object will be created, which is not only inefficient It also wastes a lot of memory space.

2. StringBuffer and StringBuilder are string variables and objects that can be changed. Unlike String, the former two types of objects can be modified multiple times without generating new unused objects.

3. The difference between StringBuffer and StringBuilder is: StringBuffer is thread-safe, and StringBuilder is an equivalent class used by a single thread newly added by JDK , that is, thread-unsafe.

So in general StringBuffer is safer (multi-threaded), StringBuilder is faster (single-threaded)


JSON JavaScript Object Notation

Currently learned data interaction formats:

  • String splicing: the client splices the information into a string and sends it to the server

    Client <—— splicing string ——> server

  • XML format: extended markup language (also splicing strings into XML format)

    • Commonly used in HTML
    • Disadvantages : relatively heavy, troublesome - packing and unpacking trouble (adding a lot of new characters)
  • JSON format:

1. Understand JSON

  • JavaScript Object Notation A lightweight data interchange format. Easy for humans to read and write, enabling data exchange between multiple languages
    • Easy to machine parse and generate.
    • In essence, it is to convert the object -- to --> string

2. Two structures of JSON

  • Objects are denoted by braces{}

  • Lists are denoted by square brackets[]

  • The syntax is as follows

    [
        {
          
          
            key1:value1,
            key2:value2 
        },
        {
          
          
             key3:value3,
             key4:value4   
        }
    ]
    
  • for example

    // 对象:
    {
          
          
    "friendId":"1001",
    "groupId":7,
    "qqid":"1003",
    "friendName":"小美1"
    }
    // 列表,(存放多个对象时可以分别用大括号表示
    [
        {
          
          
            "friendId":"1001",
    		"groupId":7,
    		"qqid":"1003",
    		"friendName":"小美1"
        },
        {
          
          
             "friendId":"1001",
    		"groupId":7,
    		"qqid":"1003",
    		"friendName":"小美1"
        }
    ]
    

3. Usage of JSON

JSON is a specification, so it provides a toolkit, here we use Alibaba's packageFASTJSON.jar

The JSON usage shown here is based on the FASTJSON package.

The latest download address github.com/alibaba/fastjson/wiki

⭐️Conversion between JSON strings, JSON objects, Bean objects, and collection objects

  • important! ! Attention should be paid to the attribute permissions of the object! Classes and properties also require public permissions or public access methods

  • string - object

    • JSONObject.toJSONString: object to string
    • JSONObject.parseObject(字符串, 类名.class);: convert the string to the corresponding object
  • string - collection object

    • JSONArray.toJSONString: Set to string
    • JSONArray.parseArray(字符串, 元素类名.class): string to collection
  • string - JSON object

    • JSONObject It is essentially an object in map format that stores key-value pairs. put(key,value)Elements can be inserted using
    • JSONObject.toJSONStringSame, object to string
    • JSONObject jsonObjNew = JSONObject.parseObject(jsonStr);: string to JSON object
package com;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

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

public class JSONDemo2 {
    
    
    public static void main(String[] args) {
    
    
        // 声明学生对象
        Student stu1 = new Student("小A" , 15 , 001 ,"福建省厦门市思明区");
        Student stu2 = new Student("小B" , 11 , 002 ,"福建省福州市鼓楼区");
        Student stu3 = new Student("小C" , 17 , 003 ,"福建省泉州市丰泽区");

        // 声明一个列表存储对象
        ArrayList<Student> stuList = new ArrayList<>();
        stuList.add(stu1);
        stuList.add(stu2);
        stuList.add(stu3);

        // 1、JSON 字符串 —— 对象
        String stu1Json = JSONObject.toJSONString(stu1);
        System.out.println("对象转字符串:"+stu1Json);

        Student stu1New = JSONObject.parseObject(stu1Json , Student.class);
        System.out.println("字符串转对象:  "+stu1New);

        // 2JSON字符串 —— 集合对象
        String listJson = JSONArray.toJSONString(stuList);
        System.out.println("集合转字符串:"+listJson);

        List<Student> studentList = JSONArray.parseArray(listJson, Student.class);
        System.out.println("字符串转数组:(长度)"+ studentList.size()+"(内容)"+studentList.get(0)+studentList.get(1)+studentList.get(2));

        // 3 JSON字符串 —— JSON对象
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type","学生信息");
        jsonObject.put("list",stuList); // json对象存放数组
        jsonObject.put("object",stu1);  // json对象存放对象

        String jsonStr = JSONObject.toJSONString(jsonObject);
        System.out.println("JSON对象转字符串:"+jsonStr);

        JSONObject jsonObjNew = JSONObject.parseObject(jsonStr);
        System.out.println(jsonObjNew.get("type"));
        System.out.println(jsonObjNew.get("list"));
        System.out.println(jsonObjNew.get("object"));
    }
}
package com;

public class Student {
    
    
    public String name;
    public int age;
    public int stuID;
    public String address;

    public Student(String name, int age, int stuID, String address) {
    
    
        this.name = name;
        this.age = age;
        this.stuID = stuID;
        this.address = address;
    }

    @Override
    public String toString() {
    
    
        return "Student类的值为:{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", stuID=" + stuID +
                ", address='" + address + '\'' +
                '}';
    }
}
输出结果
对象转字符串:{"address":"福建省厦门市思明区","age":15,"name":"小A","stuID":1}
字符串转对象:  Student类的值为:{name='小A', age=15, stuID=1, address='福建省厦门市思明区'}

集合转字符串:[{"address":"福建省厦门市思明区","age":15,"name":"小A","stuID":1},{"address":"福建省福州市鼓楼区","age":11,"name":"小B","stuID":2},{"address":"福建省泉州市丰泽区","age":17,"name":"小C","stuID":3}]
字符串转数组:(长度)3(内容)Student类的值为:{name='小A', age=15, stuID=1, address='福建省厦门市思明区'}Student类的值为:{name='小B', age=11, stuID=2, address='福建省福州市鼓楼区'}Student类的值为:{name='小C', age=17, stuID=3, address='福建省泉州市丰泽区'}

JSON对象转字符串:{"type":"学生信息","list":[{"address":"福建省厦门市思明区","age":15,"name":"小A","stuID":1},{"address":"福建省福州市鼓楼区","age":11,"name":"小B","stuID":2},{"address":"福建省泉州市丰泽区","age":17,"name":"小C","stuID":3}],"object":{"$ref":"$.list[0]"}}

学生信息
[{"address":"福建省厦门市思明区","stuID":1,"name":"小A","age":15},{"address":"福建省福州市鼓楼区","stuID":2,"name":"小B","age":11},{"address":"福建省泉州市丰泽区","stuID":3,"name":"小C","age":17}]
{"address":"福建省厦门市思明区","stuID":1,"name":"小A","age":15}

4. How to let the client judge what object is accepted?

Because the JSON object is essentially the type of key-value pair (MAP), the object to be passed can be packaged as a JSONObject object

Specific methods (sender, packaging)

  1. Create a JSONObject object
  2. The method used put(key,value)to store information in
  3. The first information is fixed to indicate the type of object storage
  4. Convert this object to a string in JSON format
  5. Just pass this string

(receiving end: pack

  1. Use JSONObject.parseObjectthe method to convert a string to a JSONObject object

  2. Use the member method of JSONObject to get the corresponding value

    • getString(key): get a string type object

    • getJSONArray: Obtain a list-type object. specific conversion method

      JSONArray jsonAry = jsonObject.getJSONArray("list");
      List<QQGroup> list = jsonAry.toJavaList(QQ.class);
      

Supplementary knowledge points: XML language (Extensible Markup Language).

  • XML stands for Extensible Markup Language. It is a markup language that is simplified and modified from Standard Generalized Markup Language (SGML). It mainly uses Extensible Markup Language, Extensible Style Language (XSL), XBRL and XPath.

  • XML has the following characteristics:

    1. XML can separate data from HTML
    2. XML can be used to exchange data. Based on XML, data can be exchanged between incompatible systems. Converting data to XML format storage will greatly reduce the complexity of exchanging data, and can also make these data readable by different programs.
    3. XML can be applied in B2B. XML is now becoming the primary language used to exchange information between business systems spread across the Web. For example, exchanging financial information in the network.
    4. Data can be shared using XML. XML data is stored in plain text format, which makes data sharing between different systems and programs easier.
    5. XML can take full advantage of data. Just like operating a database, XML data can be processed by various "readers"
    6. XML can be used to create new languages. Both WAP and WML languages ​​are developed from XML.

    In short, XML uses a simple and flexible standard format to provide an effective means of describing data and exchanging data for Web-based applications. However, XML is not intended to replace HTML. HTML focuses on how to describe how to display files in the browser, while XML is similar to SGML, which focuses on describing how to represent data in a structured way.

Supplementary knowledge points: the difference between XML and JSON

1. JSON is JavaScript Object Notation; XML is Extensible Markup Language.

2. JSON is based on the JavaScript language; XML is derived from SGML.

3. JSON is a way of representing objects; XML is a markup language that uses markup structures to represent data items.

4. JSON does not provide any support for namespaces; XML supports namespaces.

5. JSON supports arrays; XML does not support arrays.

6. XML files are relatively difficult to read and interpret; JSON files are very easy to read compared to XML.

7. JSON does not use end tags; XML has start and end tags.

8. JSON is less secure; XML is more secure than JSON.

9. JSON does not support comments ; XML supports comments.

10. JSON only supports UTF-8 encoding; XML supports various encodings

original

Guess you like

Origin blog.csdn.net/Xcong_Zhu/article/details/126082889