[JavaSE Column 88] Conversion of Java strings and JSON objects, just like this!

Author homepage : Designer Xiao Zheng
Author brief introduction : 3 years of JAVA full-stack development experience, focusing on JAVA technology, system customization, remote guidance, dedicated to enterprise digital transformation, certified lecturer of CSDN College and Blue Bridge Cloud Course.
Main direction : Vue, SpringBoot, WeChat applet

This article explains the concept of JSON, the conversion method of JSON objects and strings in Java, and gives sample codes. JSON is a lightweight data exchange format, which is often used for data transmission in Web applications.

Insert image description here


1. What is JSON

JSON is a lightweight data interchange format commonly used for data transmission in web applications .

JSON is based on JavaScriptsyntax, but can be parsed and generated by a variety of programming languages.

JSON uses key-value pairs to represent data, where the key is a string and the value can be a string, number, Boolean value, object, array or null. It has the following 5 5Students can simply understand the 5 characteristics .

  1. Simplicity : JSON uses a simple syntax to represent data, making it easy to read and write.
  2. Readability : The text format of JSON is plain text and can be easily understood by humans and machines.
  3. Cross-language support : JSON is a language-independent data format that can be parsed and generated by multiple programming languages.
  4. Flexible data structure : JSON supports complex data structures and can nest objects and arrays.
  5. High data transmission efficiency : JSON has a small data volume and fast transmission speed, making it suitable for network transmission.

Insert image description here

2. Application scenarios of JSON

JSON has a wide range of application scenarios in various applications. The following are some common application scenarios. Please study carefully.

  1. Front-end and back-end data interaction : JSON is often used for front-end and back-end data interaction. The server-side data can be sent to the front-end in JSON format, and the front-end uses JavaScript to parse the JSON data for display and processing.
  2. API interface design : Many web service API interfaces use JSON as the data exchange format. Data transmission and interaction can be achieved by sending data to the API interface in JSON format.
  3. Data storage : JSON can be used to store and transmit configuration files, user preferences and other unstructured data. It can serialize data into JSON format, store it in a file or database, and re-parse it into objects when needed.
  4. Logging : JSON can be used to record log information and record complex structured data in JSON format to facilitate subsequent analysis and processing.
  5. Mobile application development : JSON is also widely used in the development of mobile applications, and can be used for data transmission, persistent storage, configuration files, etc.
  6. Data exchange : JSON, as a general data exchange format, can be used for data transmission and exchange between different systems and platforms, and realize data sharing and interoperability between systems.

In general, the flexibility, readability and cross-language support of JSON make it widely used in various fields and applications, and become a commonly used data exchange and storage format.

Insert image description here


3. Convert JSON object to string

In Java, you can use different libraries to implement the operation of converting JSON objects to strings, such as using the Jacksonlibrary and Gsonthe library.

3.1 Use the Jackson library to convert JSON objects to strings

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonExample {
    
    
    public static void main(String[] args) {
    
    
        // 创建一个对象
        MyObject myObject = new MyObject("John", 25);

        // 创建ObjectMapper对象
        ObjectMapper objectMapper = new ObjectMapper();
        
        try {
    
    
            // 将对象转换为JSON字符串
            String jsonString = objectMapper.writeValueAsString(myObject);
            System.out.println(jsonString);
        } catch (JsonProcessingException e) {
    
    
            e.printStackTrace();
        }
    }
}

class MyObject {
    
    
    private String name;
    private int age;

    public MyObject(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }

    // 省略getter和setter方法
}

3.2 Use the Gson library to convert JSON objects to strings

import com.google.gson.Gson;

public class JsonExample {
    
    
    public static void main(String[] args) {
    
    
        // 创建一个对象
        MyObject myObject = new MyObject("John", 25);

        // 创建Gson对象
        Gson gson = new Gson();
        
        // 将对象转换为JSON字符串
        String jsonString = gson.toJson(myObject);
        System.out.println(jsonString);
    }
}

class MyObject {
    
    
    private String name;
    private int age;

    public MyObject(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }

    // 省略getter和setter方法
}

Students can use the Jackson library or Gson library to convert a custom Java object into a JSON string. They can choose the appropriate library according to their own needs to implement the JSON object to string function.

Insert image description here


4. Convert JSON string to object

In Java, you can use different libraries to implement the operation of converting JSON strings to objects, such as using the Jacksonlibrary and Gsonthe library.

4.1 Use the Jackson library to implement JSON string conversion to objects

import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonExample {
    
    
    public static void main(String[] args) {
    
    
        String jsonString = "{\"name\":\"John\",\"age\":25}";

        ObjectMapper objectMapper = new ObjectMapper();
        try {
    
    
            MyObject myObject = objectMapper.readValue(jsonString, MyObject.class);
            System.out.println(myObject);
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }
}

class MyObject {
    
    
    private String name;
    private int age;

    // 省略getter和setter方法

    @Override
    public String toString() {
    
    
        return "MyObject{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

4.2 Use Gson library to convert JSON string to object

import com.google.gson.Gson;

public class JsonExample {
    
    
    public static void main(String[] args) {
    
    
        String jsonString = "{\"name\":\"John\",\"age\":25}";

        Gson gson = new Gson();
        MyObject myObject = gson.fromJson(jsonString, MyObject.class);
        System.out.println(myObject);
    }
}

class MyObject {
    
    
    private String name;
    private int age;

    // 省略getter和setter方法

    @Override
    public String toString() {
    
    
        return "MyObject{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Students can use the Jackson library or the Gson library to convert a custom JSON string into a Java object, and can choose the appropriate library according to their own needs to realize the function of converting a string to a JSON object.

Insert image description here


5. JSON interview questions

1. What is JSON? What is the full name of JSON?

JSON is a lightweight data interchange format that represents structured data in a concise text format.

2. What are the commonly used JSON processing libraries in Java?

Commonly used JSON processing libraries include Jackson, Gson, Fastjsonetc.

3. How to convert Java objects to JSON strings?

You can use the API provided by the JSON processing library, such as the method ObjectMapperin the class of the Jackson library, or the method of the library , to convert Java objects into JSON strings.writeValueAsString()GsontoJson()

4. How to convert JSON string to Java object?

You can also use the API provided by the JSON processing library, such as the method ObjectMapperin the class of the Jackson library readValue(), or the method Gsonof the library fromJson(),

5. How to deal with JSON array?

You can use the JSONArray class to process JSON arrays, get array elements by index, or use a loop to iterate over array elements.

6. How to deal with nested JSON objects?

JSON objects can be nested, and nested JSON objects can be parsed recursively, or nested JSON objects can be mapped to Java objects using object mapping.

7. What are the data types in JSON?

Data types in JSON include 字符串(String), 数字(Number), 布尔值(Boolean), 数组(Array), 对象(Object)and null.

8. How to deal with date and time in JSON?

You can convert dates and times into strings in a specific format for storage and transmission, and then convert the strings into date and time types during parsing.

9. How to deal with special characters in JSON?

In JSON, special characters need to be escaped. For example, double quotes need to be "represented by , and newlines need to be \nrepresented by .

10. How to deal with empty fields in JSON?

You can use null nulln u ll value to represent an empty field in JSON, or use a default value or an empty string according to specific needs.


6. Summary

This article explains the concept of JSON, as well as the conversion method of JSON objects and strings in Java, and gives sample code. In the next blog, the conversion of XML and strings in Java will be explained.

Insert image description here

Guess you like

Origin blog.csdn.net/qq_41464123/article/details/132521569