Easy Tutorial
❮ Android Tutorial Fragment Demo5 Coreos Setup Pc ❯

Fastjson Quick Start Guide

Category Programming Technology

Introduction to Fastjson

Fastjson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.

Fastjson can handle any Java object, including pre-existing objects for which you do not have the source code.

Fastjson Source Code: https://github.com/alibaba/fastjson

Fastjson Chinese Wiki: https://github.com/alibaba/fastjson/wiki/Quick-Start-CN


Features of Fastjson


Download and Usage

You can download directly from the Maven central repository:

https://repo1.maven.org/maven2/com/alibaba/fastjson/

Or configure Maven dependency:

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

Where x.x.x is the version number, use the specific version as needed, preferably the latest version.


Converting Java Objects to JSON Format

Define the following Person JavaBean:

Example

public class Person {
    @JSONField(name = "AGE")
    private int age;

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

    @JSONField(name = "DATE OF BIRTH")
    private Date dateOfBirth;

    public Person(int age, String fullName, Date dateOfBirth) {
        super();
        this.age = age;
        this.fullName = fullName;
        this.dateOfBirth = dateOfBirth;
    }

    // Standard getters & setters
}

You can use JSON.toJSONString() to convert a Java object to a JSON object:

private List<Person> listOfPersons = new ArrayList<Person>();

@Before
public void setUp() {
    listOfPersons.add(new Person(15, "John Doe", new Date()));
    listOfPersons.add(new Person(20, "Janette Doe", new Date()));
}

@Test
public void whenJavaList_thanConvertToJsonCorrect() {
    String jsonOutput = JSON.toJSONString(listOfPersons);
}

The output will be:

[
    {
        "AGE": 15,
        "DATE OF BIRTH": 1468962431394,
        "FULL NAME": "John Doe"
    },
    {
        "AGE": 20,
        "DATE OF BIRTH": 1468962431394,
        "FULL NAME": "Janette Doe"
    }
]

We can also customize the output, controlling field order, date display format, serialization flags, etc.

Next, we update the bean and add several fields:

@JSONField(name = "AGE", serialize = false)
private int age;

@JSONField(name = "LAST NAME", ordinal = 2)
private String lastName;

@JSONField(name = "FIRST NAME", ordinal = 1)
private String firstName;

@JSONField(name = "DATE OF BIRTH", format = "dd/MM/yyyy", ordinal = 3)
private Date dateOfBirth;

In the above code, we list basic parameter types and use the @JSONField annotation for custom conversion:

The output will then be:

[
    {
        "FIRST NAME": "Doe",
        "LAST NAME": "Jhon",
        "DATE OF BIRTH": "19/07/2016"
    },
    {
        "FIRST NAME": "Doe",
        "LAST NAME": "Janette",
        "DATE OF BIRTH": "19/07/2016"
    }
]

@JSONField

The @JSONField annotation can be applied to:

Note: FastJson operates based on getter and setter methods, not fields. Note: If a property is private, it must have a set method; otherwise, it cannot be deserialized.

package com.alibaba.fastjson.annotation;

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

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

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

    // Whether to serialize
    boolean serialize() default true;

    // Whether to deserialize
    boolean deserialize() default true;
}

2. JSONField Configuration Methods

FieldInfo can be configured on getter/setter methods or fields. For example:

2.1 Configuring on getter/setter methods

public class A {
    private int id;

    @JSONField(name = "ID")
    public int getId() { return id; }
    @JSONField(name = "ID")
    public void setId(int value) { this.id = id; }
}

2.2 Configuring on fields

public class A {
    @JSONField(name = "ID")
    private int id;

    public int getId() { return id; }
    public void setId(int value) { this.id = id; }
}

3. Using format to configure date formatting

public class A {
    // Configure date serialization and deserialization using yyyyMMdd date format
    @JSONField(format = "yyyyMMdd")
    public Date date;
}

4. Using serialize/deserialize to specify fields not to be serialized

public class A {
    @JSONField(serialize = false)
    public Date date;
}

public class A {
    @JSONField(deserialize = false)
    public Date date;
}

5. Using ordinal to specify field order

By default, fastjson serializes a Java bean based on the alphabetical order of field names. You can use ordinal to specify the order of fields. This feature requires version 1.1.42 or above.

public static class VO {
    @JSONField(ordinal = 3)
    private int f0;

    @JSONField(ordinal = 2)
    private int f1;

    @JSONField(ordinal = 1)
    private int f2;
}

FastJson also supports BeanToArray serialization:

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

The output will be:

[
    [
        15,
        1469003271063,
        "John Doe"
    ],
    [
        20,
        1469003271063,
        "Janette Doe"
    ]
]

Creating JSON Objects

Creating JSON objects is straightforward using JSONObject (provided by fastJson for JSON objects) and JSONArray (provided by fastJson for JSON arrays).

We can treat JSONObject as a Map&lt;String, Object>, but JSONObject provides richer and more convenient methods for manipulating object properties. Let's look at the source code. Similarly, we can treat a JSONArray as a List<Object>, and consider a JSONArray as a collection of JSONObject objects.

Additionally, since JSONObject and JSONArray inherit from JSON, we can directly use both to convert between JSON format strings and JSON objects as well as JavaBeans. However, to avoid confusion, we still use JSON.

@Test
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");
        jsonArray.add(jsonObject);
    }
    String jsonOutput = jsonArray.toJSONString();
}

Output result:

[
   {
      "AGE":"10",
      "DATE OF BIRTH":"2016/12/12 12:12:12",
      "FULL NAME":"Doe 0"
   },
   {
      "AGE":"10",
      "DATE OF BIRTH":"2016/12/12 12:12:12",
      "FULL NAME":"Doe 1"
   }
]

Convert JSON String to Java Object

Now that we have learned how to create JSON objects and convert Java objects to JSON strings, we need to understand how to parse JSON:

@Test
public void whenJson_thanConvertToObjectCorrect() {
    Person person = new Person(20, "John", "Doe", new Date());
    String jsonObject = JSON.toJSONString(person);
    Person newPerson = JSON.parseObject(jsonObject, Person.class);

    assertEquals(newPerson.getAge(), 0); // If we set serialization to false
    assertEquals(newPerson.getFullName(), listOfPersons.get(0).getFullName());
}

We can use JSON.parseObject() to convert a JSON string to a Java object.

Note that when deserializing to an object, it must have a default no-argument constructor, otherwise an exception will be thrown:

com.alibaba.fastjson.JSONException: default constructor not found.

Here is a simple example test:

Person [age=20, fullName=John Doe, dateOfBirth=Wed Jul 20 08:51:12 WEST 2016]

The @JSONField deserialize option can specify that a field should not be deserialized.

@JSONField(name = "DATE OF BIRTH", deserialize=false)
private Date dateOfBirth;

Output result:

Person [age=20, fullName=John Doe, dateOfBirth=null]

Configure JSON Conversion Using ContextValueFilter

In some scenarios, filtering values requires obtaining information about the owning JavaBean, including type, fields, methods, etc. In fastjson-1.2.9, ContextValueFilter is provided, similar to the ValueFilter in previous versions, but with an additional BeanContext parameter available.

@Test
public void givenContextFilter_whenJavaObject_thanJsonCorrect() {
    ContextValueFilter valueFilter = new ContextValueFilter () {
        public Object process(
          BeanContext context, Object object, String name, Object value) {
            if (name.equals("DATE OF BIRTH")) {
                return "NOT TO DISCLOSE";
            }
            if (value.equals("John")) {
                return ((String) value).toUpperCase();
            } else {
                return null;
            }
        }
    };
    String jsonOutput = JSON.toJSONString(listOfPersons, valueFilter);
}

In the above example, we hide the "DATE OF BIRTH" field and filter out fields that do not contain "John":

[
    {
        "FULL NAME":"JOHN DOE",
        "DATE OF BIRTH":"NOT TO DISCLOSE"
    }
]

Using NameFilter and SerializeConfig

NameFilter: Modify the key during serialization.

SerializeConfig: An internal map container primarily used to configure and record the serialization class corresponding to each Java type.

@Test
public void givenSerializeConfig_whenJavaObject_thanJsonCorrect() {
    NameFilter formatName = new NameFilter() {
        public String process(Object object, String name, Object value) {
            return name.toLowerCase().replace(" ", "_");
        }
    };

    SerializeConfig.getGlobalInstance().addFilter(Person.class,  formatName);
    String jsonOutput = 
      JSON.toJSONStringWithDateFormat(listOfPersons, "yyyy-MM-dd");
}

In the example, we declare the formatName filter using the NameFilter anonymous class to process field names. The newly created filter is associated with the Person class and then added to the global instance, which is a static attribute of the SerializeConfig class.

Now we can easily convert objects to JSON format.

Note that we use toJSONStringWithDateFormat() instead of toJSONString(), which can format dates more quickly.

Output result:

[  
    {  
        "full_name":"John Doe",
        "date_of_birth":"2016-07-21"
    },
    {  
        "full_name":"Janette Doe",
        "date_of_birth":"2016-07-21"
    }
]
❮ Android Tutorial Fragment Demo5 Coreos Setup Pc ❯