Main Tutorials

FastJson – Convert Java objects to / from JSON

FastJson provides easily APIs to convert Java objects to / from JSON

  • JSON.toJSONString – Java objects to JSON
  • JSON.parseObject – JSON to Java objects
  • JSON.parseArray – JSON array to List of Java objects
Note
You may have interest to read this How to parse JSON with Jackson

Overall, the FastJson is really simple and easy to convert JSON to / from objects, however, it lack of direct File support, especially the JSON.parseArray method, it needs some extra efforts to read from a JSON file. Hope the future APIs like parseObject and parseArray are able to support for sources like File or URL directly.

P.S Tested with FastJson 1.2.57

pom.xml

	<dependency>
		<groupId>com.alibaba</groupId>
		<artifactId>fastjson</artifactId>
		<version>1.2.57</version>
	</dependency>

1. POJO

A simple POJO, for JSON conversion.

Staff.java

package com.mkyong;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class Staff {

    private String name;
    private int age;
    private String[] position;
    private List<String> skills;
    private Map<String, BigDecimal> salary;

    //getters, setters, toString, constructor
}

2. Java objects to JSON

FastJsonExample1.java

package com.mkyong;

import com.alibaba.fastjson.JSON;

import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

public class FastJsonExample1 {

    public static void main(String[] args) {

        Staff staff = createStaff();

        // Java objects to JSON
        String json = JSON.toJSONString(staff);
        System.out.println(json);

        // Java objects to JSON, pretty-print
        String json2 = JSON.toJSONString(staff, true);
        System.out.println(json2);

        // Java objects to JSON, with formatted date
        String json3 = JSON.toJSONStringWithDateFormat(staff, "dd/MM/yyyy HH:mm:ss");
        System.out.println(json3);

        // List of Java objects to JSON Array
        List<Staff> list = Arrays.asList(createStaff(), createStaff());
        String json4 = JSON.toJSONStringWithDateFormat(list, "dd/MM/yyyy HH:mm:ss");
        System.out.println(json4);

        try {
            // can't find fastjson api to write files, np, just use the standard java.nio Files.write
            Files.write(Paths.get("c:\\projects\\staff.json"), json4.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static Staff createStaff() {

        Staff staff = new Staff();

        staff.setName("mkyong");
        staff.setAge(38);
        staff.setPosition(new String[]{"Founder", "CTO", "Writer"});
        Map<String, BigDecimal> salary = new HashMap() {{
            put("2010", new BigDecimal(10000));
            put("2012", new BigDecimal(12000));
            put("2018", new BigDecimal(14000));
        }};
        staff.setSalary(salary);
        staff.setSkills(Arrays.asList("java", "python", "node", "kotlin"));
        staff.setJoinDate(new Date());

        return staff;

    }

}

Output


// json
{"age":38,"joinDate":1556870430099,"name":"mkyong","position":["Founder","CTO","Writer"],
"salary":{"2018":14000,"2012":12000,"2010":10000},"skills":["java","python","node","kotlin"]}

// json2
{
	"age":38,
	"joinDate":1556870430099,
	"name":"mkyong",
	"position":["Founder","CTO","Writer"],
	"salary":{
		"2018":14000,
		"2012":12000,
		"2010":10000
	},
	"skills":[
		"java",
		"python",
		"node",
		"kotlin"
	]
}

// json3 - format date
{"age":38,"joinDate":"03/05/2019 16:00:30","name":"mkyong","position":["Founder","CTO","Writer"],
"salary":{"2018":14000,"2012":12000,"2010":10000},"skills":["java","python","node","kotlin"]}

// json4 - JSON Array
[
	{
		"age":38,
		"joinDate":1556870630615,
		"name":"mkyong",
		"position":["Founder","CTO","Writer"],
		"salary":{
			"2018":14000,
			"2012":12000,
			"2010":10000
		},
		"skills":[
			"java",
			"python",
			"node",
			"kotlin"
		]
	},
	{
		"age":38,
		"joinDate":1556870630615,
		"name":"mkyong",
		"position":["Founder","CTO","Writer"],
		"salary":{
			"2018":14000,
			"2012":12000,
			"2010":10000
		},
		"skills":[
			"java",
			"python",
			"node",
			"kotlin"
		]
	}
]

3. JSON to Java objects

FastJsonExample2.java

package com.mkyong;

import com.alibaba.fastjson.JSON;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class FastJsonExample2 {

    public static void main(String[] args) {

        // JSON string to Java object
        String jsonString = "{\"name\":38,\"name\":\"mkyong\"}";
        Staff staff = JSON.parseObject(jsonString, Staff.class);

        System.out.println(staff);

        // JSON array to Java object
        String jsonArray = "[{\"name\":38,\"name\":\"mkyong\"}, {\"name\":39,\"name\":\"mkyong2\"}]";
        List<Staff> staff1 = JSON.parseArray(jsonArray, Staff.class);

        System.out.println(staff1);

        // JSON array in File to Java object
        // staff.json contain JSON array
        try (Stream<String> lines = Files.lines(Paths.get("c:\\projects\\staff.json"))) {

            String content = lines.collect(Collectors.joining());
			// Hope parseArray() will support File or Reader in future.
            List<Staff> list = JSON.parseArray(content, Staff.class);
            System.out.println(list);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Riccardo Cossu
4 years ago

Ok but why would one choose it over established solutions like Gson (fast) or Jackson (flexible and with better defaults, but heavier than Gson)? Is it faster and/or more resource friendly than Gson?

rocky
4 years ago

How to ignore unknown properties with fastjson ?