DEV Community

Cover image for FastJSON - Convert POJO to/from JSON
Devanand Ukalkar
Devanand Ukalkar

Posted on

FastJSON - Convert POJO to/from JSON

Fastjson is a lightweight Java library created by Alibaba. It can be used to convert POJO (Plain Old Java Object) into their JSON representation & convert a JSON string to an equivalent POJO. Fastjson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

Let's dive straight into the example to look at how this library provides easy APIs to convert Java objects to / from JSON.

  • We will create one simple Maven project with following dependencies for FastJson and Lombok(for getters/setters) in pom.xml file.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>fast-json-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.7</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
        </dependency>
    </dependencies>

</project>
Enter fullscreen mode Exit fullscreen mode
  • Lets write simple POJO Employee Class and a Main class to convert it into JSON.

JSON.toJSONString() method helps to serialize Employee object to JSON string.

Employee.java

import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;

@Data
public class Employee {

    @JSONField(name = "EmployeeId")
    private Integer id;

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

    @JSONField(name = "EmployeeLocation")
    private String location;

    @JSONField(name = "EmployeeSalary")
    private Double salary;

    public Employee(Integer id, String name, String location, Double salary) {
        this.id = id;
        this.name = name;
        this.location = location;
        this.salary = salary;
    }
}

Enter fullscreen mode Exit fullscreen mode

Main.java

import com.alibaba.fastjson2.JSON;

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

public class Main {
    public static void main(String[] args) {

        List<Employee> employeeList = new ArrayList<>();

        employeeList.add(new Employee(1, "Stephen Hawking", "UK", 1000.00));
        employeeList.add(new Employee(2, "Albert Einstein", "Germany", 2000.00));

        // Convert Employee object to JSON
        String jsonString = JSON.toJSONString(employeeList);

        System.out.println(jsonString);
    }
}

Enter fullscreen mode Exit fullscreen mode

Output:

Image description

  • The JSON output is customizable with control over ordering of key-value pair. You will just need to pass an argument as ordinal = <nth order> to @JSONField
 @JSONField(name = "EmployeeLocation", ordinal = 4)
    private String location;

 @JSONField(name = "EmployeeSalary", ordinal = 3)
    private Double Salary;
Enter fullscreen mode Exit fullscreen mode

if you compare the previous output with this one, the key's positions are ordered as specified.

Image description

  • You can choose to ignore some of the fields with serialize=false parameter.
@JSONField(name = "EmployeeId", serialize = false)
    private Integer id;
Enter fullscreen mode Exit fullscreen mode
  • You can choose date formatting with format="MM/dd/YYYY" parameter.
@JSONField(name = "EmployeeDoJ", format = "MM/dd/YYYY", ordinal = 5)
    private Date dateOfJoining;
Enter fullscreen mode Exit fullscreen mode

Image description

Now, lets parse JSON to Java object. We will look at converting a JSON String, array and file to an object.

  • Converting JSON String to Object can be done using JSON.parseObject(jsonToConvert, Employee.class);. One of the things to note here is that, the Keys missing in JSON strings will be defaulted to "false". Additionally, if you choose not to deserialize any specific field, you can specify parameter as "deserialize=false" in the @JSONField annotation.
@JSONField(name = "EmployeeId", serialize = false, deserialize = false)
    private Integer id;
Enter fullscreen mode Exit fullscreen mode
// Convert JSON String to Java Object
String jsonToConvert = "{\"EmployeeName\":\"Stephen Hawking\",\"EmployeeSalary\":1000.0,\"EmployeeLocation\":\"UK\"}";
System.out.println("JSON to Convert ==> " + jsonToConvert + "\n");
Employee employeeObj = JSON.parseObject(jsonToConvert, Employee.class);
System.out.println("Converted to Employee Object ==> " + employeeObj);

Enter fullscreen mode Exit fullscreen mode

Image description

  • JSON array to Java object using JSON.parseArray(jsonArrayToConvert, Employee.class);
String jsonArrayToConvert = "[{\"EmployeeName\":\"Stephen Hawking\",\"EmployeeSalary\":1000.0,\"EmployeeLocation\":\"UK\"},{\"EmployeeName\":\"Albert Einstein\",\"EmployeeSalary\":2000.0,\"EmployeeLocation\":\"Germany\"}]";
System.out.println("JSON Array to Convert ==> " + jsonArrayToConvert + "\n");
List<Employee> employees = JSON.parseArray(jsonArrayToConvert, Employee.class);
System.out.println("Converted to Employee Objects ==> " + employees);
Enter fullscreen mode Exit fullscreen mode

Image description

  • JSON file to Java Object --> FastJson bit lacks in direct JSON file support, it needs some extra code to to read from JSON file.

JSON File:
Image description

// Convert JSON File to Java Object
try (Stream<String> lines = Files.lines(Paths.get("employees.json"))) {
    String jsonContent = lines.collect(Collectors.joining());
    List<Employee> empList = JSON.parseArray(jsonContent, Employee.class);
    System.out.println("Converted to Java Object ==> " + empList);
} catch (IndexOutOfBoundsException | IOException ex) {
    ex.printStackTrace();
}
Enter fullscreen mode Exit fullscreen mode

Image description

You can checkout more examples on below GitHub Repository.
https://github.com/eugenp/tutorials/tree/master/json-modules/json-2

Leave your reactions and comments below if you found this information useful! Cheers!!

Top comments (0)