SoFunction
Updated on 2025-04-06

Java fastjson2 Analyzing JSON usage detailed explanation

Fastjson2yesFastjsonThe upgraded version provides better performance and scalability, and has also made many improvements in API and functionality. useFastjson2Parsing JSON data is very simple and supports multiple ways to parse JSON strings, nested JSON objects and arrays, and convert them into Java objects. The following details are introducedFastjson2Common JSON parsing usage.

1. Introducing Fastjson2 dependencies

In useFastjson2Before, make sure that the project contains the corresponding dependencies.

Maven dependencies

<dependency>
    <groupId>.fastjson2</groupId>
    <artifactId>fastjson2</artifactId>
    <version>2.0.31</version> <!-- Use the latest version -->
</dependency>

Gradle dependencies

implementation '.fastjson2:fastjson2:2.0.31'

2. JSON parsing

2.1 Parsing JSON strings as Java objects

Fastjson2use()Method converts a JSON string to a Java object.

Example: Parsing a JSON string into a Java object

import .;
public class Fastjson2Example {
    public static void main(String[] args) {
        String jsonString = "{\"name\":\"John\",\"age\":25}";
        // parse JSON strings as Java objects        Person person = (jsonString, );
        (());  // Output: John        (());   // Output: 25    }
}
class Person {
    private String name;
    private int age;
    // Getters and Setters
    public String getName() { return name; }
    public void setName(String name) {  = name; }
    public int getAge() { return age; }
    public void setAge(int age) {  = age; }
}

2.2 Parsing nested JSON objects

Fastjson2Nested JSON objects can be parsed directly. You can passgetJSONObject()Get nestedJSONObject, and then continue to parse it.

Example: parsing nested JSON objects

import .;
import .;
public class Fastjson2Example {
    public static void main(String[] args) {
        String jsonString = "{\"name\":\"John\",\"address\":{\"city\":\"Anytown\",\"street\":\"123 Main St\"}}";
        // parse the JSON string to JSONObject        JSONObject jsonObject = (jsonString);
        // Get nested JSON objects (address)        JSONObject address = ("address");
        String city = ("city");
        String street = ("street");
        ("City: " + city);      // Output: Anytown        ("Street: " + street);  // Output: 123 Main St    }
}

2.3 Parsing JSON arrays

Fastjson2You can also directly parse the JSON array string intoJSONArray. You can passparseArray()orparseObject()Method to process arrays.

Example: parsing JSON arrays

import .;
import .;
public class Fastjson2Example {
    public static void main(String[] args) {
        String jsonArrayString = "[{\"name\":\"John\",\"age\":25}, {\"name\":\"Jane\",\"age\":28}]";
        // parse the JSON array to List        JSONArray jsonArray = (jsonArrayString);
        // Iterate through the JSON array and parse each object        for (int i = 0; i < (); i++) {
            Person person = (i, );
            (() + " - " + ());
        }
    }
}

2.4 Parsing the JSON string to Map

If you don't need to parse JSON into a specific Java object, you can parse it directly intoMaporList

Example: parse JSON toMap

import .;
import ;
public class Fastjson2Example {
    public static void main(String[] args) {
        String jsonString = "{\"name\":\"John\",\"age\":25}";
        // parse JSON to Map        Map<String, Object> map = (jsonString, );
        // Output Map content        (map);  // Output: {name=John, age=25}    }
}

2.5 Type conversion when parsing JSON data

Fastjson2Supports complex type conversion. You can parse JSON toListMap, and any Java type.

Example: JSON conversion toListandMap

import .;
import ;
import ;
public class Fastjson2Example {
    public static void main(String[] args) {
        String jsonArrayString = "[{\"name\":\"John\",\"age\":25}, {\"name\":\"Jane\",\"age\":28}]";
        // Parses JSON array strings to List        List<Map<String, Object>> personList = (jsonArrayString, );
        (personList);  // Output: [{name=John, age=25}, {name=Jane, age=28}]    }
}

3. Advanced features

3.1 Extract data from JSON using JSONPath

Fastjson2ProvidedJSONPathFunction, supports complex query operations, similar to the functions of XPath. Available()to extract JSON data.

Example: UseJSONPathExtract JSON data

import .;
import .;
public class Fastjson2Example {
    public static void main(String[] args) {
        String jsonString = "{\"name\":\"John\", \"address\":{\"city\":\"Anytown\",\"street\":\"123 Main St\"}}";
        // Use JSONPath to extract city information        Object city = ((jsonString), "$.");
        ("City: " + city);  // Output: Anytown    }
}

3.2 Handling custom date formats

You canFastjson2Set custom date formats throughSerializeConfigConfiguration.

Example: Custom date format

import .;
import .;
import ;
import ;
public class Fastjson2Example {
    public static void main(String[] args) {
        Date date = new Date();
        // Set custom date format        SerializeConfig config = new SerializeConfig();
        (, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        // Convert date object to JSON string        String jsonString = (date, config);
        (jsonString);  // Output: 2025-01-13 14:30:00    }
}

3.3 Handling empty fields during deserialization

Fastjson2When deserializing JSON, if some fields are empty or do not exist, it will automatically skip the field and will not throw an exception. You can use@JSONFieldAnnotations to control the serialization and deserialization behavior of fields.

Example: Processing empty fields

import .;
import .;
public class Fastjson2Example {
    public static void main(String[] args) {
        String jsonString = "{\"name\":\"John\",\"age\":null}";
        // Ignore empty fields when parsing JSON strings        Person person = (jsonString, );
        (());  // Output: John        (());   // Output: 0 (default value)    }
}
class Person {
    private String name;
    @JSONField(serialize = false)  // Not serialized    private int age;
    // Getters and Setters
    public String getName() { return name; }
    public void setName(String name) {  = name; }
    public int getAge() { return age; }
    public void setAge(int age) {  = age; }
}

4. Summary

Fastjson2Provides powerful and concise JSON parsing capabilities, including:

  • Easily parse JSON strings into Java objects orMap
  • Supports parsing of nested JSON objects, arrays, and complex types.
  • SupportedJSONPathExtract data from JSON data.
  • Custom date format and serialization configuration.
  • Handle empty fields, field filtering, etc. during deserialization.

These characteristics makeFastjson2Become an efficient and feature-rich JSON parsing tool suitable for a variety of Java application scenarios.

This is the end of this article about java fastjson2 parsing JSON usage analysis. For more related java fastjson2 parsing JSON content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!