fastjson easy tutorial

fastjson easy tutorial

brief introduction

java's JSON serialization library. It provides two kinds of parsing tools, server and Android, with better performance than that of Gson and Jackson.

  1. toJSONString(object) converts an object to a JSON string
  2. parseobject(JSON) is responsible for converting JSON strings to objects.
  3. Allow conversion of immutable objects with lines
  4. Support introspection
  5. Allow custom representation of objects and custom serialization classes
  6. Support any complex object

Configuration and use

install and configure

MAVEN coordinates:



Quick start

class test {
	private List<Person> people = new LinkedList<Person>();
	public void parseToJSON(){
		people.add(new Person(15, "yichen", new Date());
		people.add(new Person(88, "leitong", new Date());
		String json = JSON.toJSONString(people);

Execution result:

        "DATE OF BIRTH":1468962431394,
        "FULL NAME":"John Doe"
        "DATE OF BIRTH":1468962431394,
        "FULL NAME":"Janette Doe"

@JSONField annotation and all configuration parameters

Can act on:

  1. Field
  2. Setter getter

Configuration parameters available for this annotation:


public @interface JSONField {
    // Configure the sequence of serialization and deserialization, which is only supported after version 1.1.42
    int ordinal() default 0;

     // Specify the name of the field
    String name() default "";

    // Specifies the format of the field, useful for date formats
    String format() default "";

    // Serialization or not
    boolean serialize() default true;

    // Deserialization or not
    boolean deserialize() default true;


fastjson also supports BeanToArray serialization:

String jsonOutput= JSON.toJSONString(people, SerializerFeature.BeanToArray);

The execution result is:

        "John Doe"
        "Janette Doe"

Creating JSON objects

There are two types of JSON objects built in:

  1. JSONObject
  2. JSONArray

JSONObject is actually a map and extends more operations. JSONArray is actually a list, which is a collection of JSONObject objects.


public void whenGenerateJson_thanGenerationCorrect() throws ParseException {
    JSONArray jsonArray = new JSONArray();
    for (int i = 0; i < 2; i++) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("AGE", 10);
        jsonObject.put("FULL NAME", "Doe " + i);
        jsonObject.put("DATE OF BIRTH", "2016/12/12 12:12:12");
    String jsonOutput = jsonArray.toJSONString();


      "DATE OF BIRTH":"2016/12/12 12:12:12",
      "FULL NAME":"Doe 0"
      "DATE OF BIRTH":"2016/12/12 12:12:12",
      "FULL NAME":"Doe 1"

Tags: JSON Java Android Maven

Posted on Thu, 07 Nov 2019 14:45:19 -0500 by elthomo