Guide to Fastjson in Java

Introduction to Fastjson

Fastjson is a powerful JSON processing library written in Java. It provides functionalities to convert Java objects to JSON and vice versa, with high performance and simplicity. This guide covers all use cases, including basic serialization and deserialization, custom configurations, and advanced features.

Installation

Adding Fastjson to Your Project

To use Fastjson, add the following dependency to your pom.xml if you're using Maven:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.83</version> <!-- or the latest version -->
</dependency>

For Gradle:

implementation 'com.alibaba:fastjson:1.2.83'

Getting Started with Fastjson

Serialization: Converting Java Objects to JSON

Serialization is the process of converting a Java object into JSON format.

import com.alibaba.fastjson.JSON;

public class SerializationExample {
    public static void main(String[] args) {
        User user = new User(1, "Amit Sharma", 30);
        String jsonString = JSON.toJSONString(user);
        System.out.println(jsonString);
    }
}

class User {
    private int id;
    private String name;
    private int age;

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

    // Getters and Setters omitted for brevity
}

Output:

{"age":30,"id":1,"name":"Amit Sharma"}

Deserialization: Converting JSON to Java Objects

Deserialization is the process of converting JSON data into Java objects.

import com.alibaba.fastjson.JSON;

public class DeserializationExample {
    public static void main(String[] args) {
        String jsonString = "{\"age\":30,\"id\":1,\"name\":\"Amit Sharma\"}";
        User user = JSON.parseObject(jsonString, User.class);
        System.out.println("ID: " + user.getId());
        System.out.println("Name: " + user.getName());
        System.out.println("Age: " + user.getAge());
    }
}

class User {
    private int id;
    private String name;
    private int age;

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

    // Getters and Setters omitted for brevity
}

Output:

ID: 1
Name: Amit Sharma
Age: 30

Advanced Serialization and Deserialization

Serializing Collections

import com.alibaba.fastjson.JSON;
import java.util.Arrays;
import java.util.List;

public class SerializeCollectionExample {
    public static void main(String[] args) {
        List<User> users = Arrays.asList(
            new User(1, "Amit Sharma", 30),
            new User(2, "Rajesh Kumar", 25)
        );
        String jsonString = JSON.toJSONString(users);
        System.out.println(jsonString);
    }
}

class User {
    private int id;
    private String name;
    private int age;

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

    // Getters and Setters omitted for brevity
}

Output:

[{"age":30,"id":1,"name":"Amit Sharma"},{"age":25,"id":2,"name":"Rajesh Kumar"}]

Deserializing Collections

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import java.util.List;

public class DeserializeCollectionExample {
    public static void main(String[] args) {
        String jsonString = "[{\"age\":30,\"id\":1,\"name\":\"Amit Sharma\"},{\"age\":25,\"id\":2,\"name\":\"Rajesh Kumar\"}]";
        List<User> users = JSON.parseObject(jsonString, new TypeReference<List<User>>() {});
        for (User user : users) {
            System.out.println("ID: " + user.getId());
            System.out.println("Name: " + user.getName());
            System.out.println("Age: " + user.getAge());
        }
    }
}

class User {
    private int id;
    private String name;
    private int age;

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

    // Getters and Setters omitted for brevity
}

Output:

ID: 1
Name: Amit Sharma
Age: 30
ID: 2
Name: Rajesh Kumar
Age: 25

Using Annotations for Custom Serialization and Deserialization

Fastjson provides annotations for customizing JSON serialization and deserialization.

@JSONField Annotation

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;

public class CustomAnnotationExample {
    public static void main(String[] args) {
        User user = new User(1, "Amit Sharma", 30);
        String jsonString = JSON.toJSONString(user);
        System.out.println(jsonString);

        String customJson = "{\"identifier\":1,\"fullName\":\"Amit Sharma\",\"age\":30}";
        User customUser = JSON.parseObject(customJson, User.class);
        System.out.println("ID: " + customUser.getId());
        System.out.println("Name: " + customUser.getName());
        System.out.println("Age: " + customUser.getAge());
    }
}

class User {
    @JSONField(name = "identifier")
    private int id;

    @JSONField(name = "fullName")
    private String name;

    private int age;

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

    // Getters and Setters omitted for brevity
}

Output:

{"age":30,"fullName":"Amit Sharma","identifier":1}
ID: 1
Name: Amit Sharma
Age: 30

Advanced Features

Handling Date and Time

Fastjson can handle date and time fields during serialization and deserialization.

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import java.util.Date;

public class DateHandlingExample {
    public static void main(String[] args) {
        User user = new User(1, "Amit Sharma", new Date());
        String jsonString = JSON.toJSONString(user);
        System.out.println(jsonString);

        String dateJson = "{\"id\":1,\"name\":\"Amit Sharma\",\"registrationDate\":\"2024-05-17 12:00:00\"}";
        User userWithDate = JSON.parseObject(dateJson, User.class);
        System.out.println("ID: " + userWithDate.getId());
        System.out.println("Name: " + userWithDate.getName());
        System.out.println("Registration Date: " + userWithDate.getRegistrationDate());
    }
}

class User {
    private int id;
    private String name;

    @JSONField(format = "yyyy-MM-dd HH:mm:ss")
    private Date registrationDate;

    public User(int id, String name, Date registrationDate) {
        this.id = id;
        this.name = name;
        this.registrationDate = registrationDate;
    }

    // Getters and Setters omitted for brevity
}

Output:

{"id":1,"name":"Amit Sharma","registrationDate":"2024-05-17 12:00:00"}
ID: 1
Name: Amit Sharma
Registration Date: Fri May 17 12:00:00 IST 2024

Serializing and Deserializing Nested Objects

import com.alibaba.fastjson.JSON;

public class NestedObjectExample {
    public static void main(String[] args) {
        Address address = new Address("MG Road", "Bengaluru", "Karnataka");
        User user = new User(1, "Amit Sharma", 30, address);
        String jsonString = JSON.toJSONString(user);
        System.out.println(jsonString);

        String nestedJson = "{\"address\":{\"city\":\"Bengaluru\",\"state\":\"Karnataka\",\"street\":\"MG Road\"},\"age\":30,\"id\":1,\"name\":\"Amit Sharma\"}";
        User userWithAddress = JSON.parseObject(nestedJson, User.class);
        System.out.println("ID: " + userWithAddress.getId());
        System.out.println("Name: " + userWithAddress.getName());
        System.out.println("Age: " + userWithAddress.getAge());
        System.out.println("Address: " + userWithAddress.getAddress().getStreet() + ", " + userWithAddress.getAddress().getCity() + ", " + userWithAddress.getAddress().getState());
    }
}

class User {
    private int id;
    private String name;
    private int age;
    private Address address;

    public User(int id, String name, int age, Address address) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.address = address;
    }

    // Getters and Setters omitted for brevity
}

class Address {
    private String street;
    private String city;
    private String state;

    public Address(String

 street, String city, String state) {
        this.street = street;
        this.city = city;
        this.state = state;
    }

    // Getters and Setters omitted for brevity
}

Output:

{"address":{"city":"Bengaluru","state":"Karnataka","street":"MG Road"},"age":30,"id":1,"name":"Amit Sharma"}
ID: 1
Name: Amit Sharma
Age: 30
Address: MG Road, Bengaluru, Karnataka

Custom Serialization and Deserialization Using JSONType

You can customize the serialization and deserialization process using the @JSONType annotation.

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONType;

public class CustomTypeExample {
    public static void main(String[] args) {
        User user = new User(1, "Amit Sharma", 30);
        String jsonString = JSON.toJSONString(user);
        System.out.println(jsonString);

        String customJson = "{\"age\":30,\"identifier\":1,\"name\":\"Amit Sharma\"}";
        User customUser = JSON.parseObject(customJson, User.class);
        System.out.println("ID: " + customUser.getId());
        System.out.println("Name: " + customUser.getName());
        System.out.println("Age: " + customUser.getAge());
    }
}

@JSONType(orders = {"identifier", "name", "age"})
class User {
    private int id;

    private String name;

    private int age;

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

    // Getters and Setters omitted for brevity
}

Output:

{"identifier":1,"name":"Amit Sharma","age":30}
ID: 1
Name: Amit Sharma
Age: 30

Handling Circular References

Fastjson can handle circular references using the SerializerFeature.DisableCircularReferenceDetect feature.

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class CircularReferenceExample {
    public static void main(String[] args) {
        User user = new User(1, "Amit Sharma");
        Department department = new Department(1, "Engineering");
        user.setDepartment(department);
        department.setUser(user);

        String jsonString = JSON.toJSONString(user, SerializerFeature.DisableCircularReferenceDetect);
        System.out.println(jsonString);
    }
}

class User {
    private int id;
    private String name;
    private Department department;

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }

    // Getters and Setters omitted for brevity
}

class Department {
    private int id;
    private String name;
    private User user;

    public Department(int id, String name) {
        this.id = id;
        this.name = name;
    }

    // Getters and Setters omitted for brevity
}

Output:

{"department":{"id":1,"name":"Engineering","user":{"id":1,"name":"Amit Sharma"}},"id":1,"name":"Amit Sharma"}

Conclusion

Fastjson is a powerful and flexible JSON processing library for Java. This guide covered the basics of serialization and deserialization, handling collections, using annotations for custom serialization, handling date and time, serializing nested objects, custom serialization and deserialization using JSONType, and handling circular references. By leveraging Fastjson, you can efficiently handle JSON in your Java applications. For more detailed information and advanced features, refer to the official Fastjson documentation.

Comments