Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Working with FastJson for JSON Serialization and Deserialization in Java

Tech 1

FastJson is an open-source JSON parsing library developed by Alibaba, capable of parsing JSON-formatted strings, serializing Java Beans into JSON strings, and deserializing JSON strings back into Java Beans.

To include FastJson in your project, add the following Maven dependency:

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

The com.alibaba.fastjson.JSON class serves as the entry point for FastJson's API, providing core functionality. Ensure that classes to be converted have a default no-argument constructor.

String to JSON Conversion

For string processing, determine whether the string (jsonStr) is in JSON object or JSON array format, then use the appropriate method.

Convert a JSON object string to a JSON object:

JSONObject jsonObj = JSON.parseObject(jsonStr);

Convert a JSON array string to a JSON array:

JSONArray jsonArr = JSON.parseArray(jsonStr);
int size = jsonArr.size(); // Get array element count
List<TrackNodeDto> nodes = jsonArr.toJavaList(TrackNodeDto.class); // Convert to specific List

String to JavaBean Conversion

Model model = JSON.parseObject(jsonStr, Model.class);

Object to String Conversion

Convert JSONObject, JSONArray, JavaBean, arrays, List, Set, or Map to a string:

String jsonStr = JSON.toJSONString(object);

Generic Deserialization

Note: The VO class must have a default no-argument constructor.

List<VO> list = JSON.parseObject("jsonString", new TypeReference<List<VO>>(){});

Key Classes

  • SerializeWriter: Functions like a StringBuffer.
  • JSONArray: Equivalent to a List.
  • JSONObject: Equivalent to a Map.

Property Filtering with SimplePropertyPreFilter

Use SimplePropertyPreFilter for customizing serialized properties based on environment needs.

public class SimplePropertyPreFilter implements PropertyPreFilter {
    public SimplePropertyPreFilter(String... properties) {
        this(null, properties);
    }

    public SimplePropertyPreFilter(Class<?> clazz, String... properties) {
        // Implementation details
    }

    public Class<?> getClazz() {
        return clazz;
    }

    public Set<String> getIncludes();
    public Set<String> getExcludes();
    // Additional methods
}

Configure includes and excludes. When clazz is not null, it applies to a specific type; when null, it appplies to all types. If includes has elements, only properties in includes are serialized, with excludes taking precedence.

Usage example (available from version 1.1.23):

User user = new User();
user.setName("shamo");
user.setPwd("123");
user.setAge(25);

SimplePropertyPreFilter filter = new SimplePropertyPreFilter(User.class, "pwd", "age");
Set<String> includes = filter.getIncludes();
Set<String> excludes = filter.getExcludes();
includes.add("name");
excludes.add("pwd");
String json = JSON.toJSONString(user, filter);
System.out.println(json);

Output:

{"age":25,"name":"shamo"}

JSONField Annotation

This annotation configures JavaBeans and can be applied to getter/setter methods, fields, or directly to properties. Note: Private properties require setter methods for deserialization.

Key attributes:

@JSONField(ordinal=1) // Configures serialization order (supported from version 1.1.42)
@JSONField(serialize=false) // Excludes field from serialization (cannot filter final fields)
@JSONField(deserialize=false) // Excludes field from deserialization (cannot filter final fields)
@JSONField(format="yyyy-MM-dd HH:mm:ss") // Serializes dates with specified format
@JSONField(name="alias") // Uses field alias
@JSONField(serializeFeatures={SerializerFeature.Property}) // Serialization rules
@JSONField(parseFeatures={Feature.Property}) // Deserialization rules

SerializerFeature Enum

Commmon properties include:

  • QuoteFieldNames: Outputs keys with double quotes (default true).
  • UseSingleQuotes: Uses single quotes instead of double quotes.
  • WriteMapNullValue: Outputs null-valued fields.
  • WriteEnumUsingToString: Outputs enum values using toString().
  • WriteEnumUsingName: Outputs enum values using name().
  • UseISO8601DateFormat: Outputs dates in ISO8601 format.
  • WriteNullListAsEmpty: Outputs null lists as empty arrays.
  • WriteNullStringAsEmpty: Outputs null strings as empty strings.
  • WriteNullNumberAsZero: Outputs null numbers as zero.
  • WriteNullBooleanAsFalse: Outputs null booleans as false.
  • SkipTransientField: Ignores transient fields in serialization.
  • SortField: Sorts fields by name in output.
  • PrettyFormat: Formats output for readability.
  • WriteClassName: Includes type information in serialization.
  • DisableCircularReferenceDetect: Disables circular reference detection.
  • BrowserCompatible: Serializes Chinese characters to \uXXXX format.
  • WriteDateUseDateFormat: Uses global date format.
  • BeanToArray: Converts objects to arrays for output.

Feature Enum

Common properties include:

  • AutoCloseSource: Automatically closes input sources (default true).
  • AllowComment: Allows Java/C++ style comments in JSON.
  • AllowUnQuotedFieldNames: Allows unquoted field names.
  • AllowSingleQuotes: Allows single quotes for strings and feild names.
  • InternFieldNames: Interns field names.
  • AllowISO8601DateFormat: Automatically converts ISO8601 date strings to Date objects.
  • AllowArbitraryCommas: Skips multiple commas.
  • UseBigDecimal: Uses BigDecimal for numbers instead of double.
  • IgnoreNotMatch: Ignores non-matching fields.
  • SortFeidFastMatch: Optimizes parsing with sorted field names.
  • DisableASM: Disables ASM optimization.
  • DisableCircularReferenceDetect: Disables circular reference detection.
  • InitStringFieldAsEmpty: Initializes empty string fields as empty strings.
  • SupportArrayToBean: Supports array-to-object conversion.
  • OrderedField: Maintains original field order.
  • DisableSpecialKeyDetect: Disables special character checking.
  • UseObjectArray: Uses object arrays.

Example JavaBean and Test

Define a User class with JSONField annotations:

class User {
    @JSONField(ordinal=4, name="ID")
    private Integer id;

    @JSONField(ordinal=3, serialize=false)
    private String name;

    @JSONField(ordinal=2, deserialize=false)
    private Integer age;

    @JSONField(ordinal=1, format="yyyy-MM-dd")
    private Date creattime;

    @JSONField(serializeFeatures=SerializerFeature.WriteMapNullValue)
    private String phone;

    // Getters and setters
    public Integer getId() { return id; }
    public void setId(Integer id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public Integer getAge() { return age; }
    public void setAge(Integer age) { this.age = age; }
    public Date getCreattime() { return creattime; }
    public void setCreattime(Date creattime) { this.creattime = creattime; }
    public String getPhone() { return phone; }
    public void setPhone(String phone) { this.phone = phone; }

    @Override
    public String toString() {
        return "id=" + id + "; name=" + name + "; age=" + age + "; createtime=" + creattime;
    }
}

Test serialization and deserialization:

User user = new User();
user.setId(123456);
user.setName("wangbo");
user.setAge(28);
user.setCreattime(new Date());

String userStr = JSON.toJSONString(user);
System.out.println(userStr);

User user2 = JSON.parseObject(userStr, User.class);
System.out.println(user2);

Output:

{"phone":null,"creattime":"2018-12-04","age":28,"ID":123456}
id=123456; name=null; age=null; createtime=Tue Dec 04 00:00:00 CST 2018

Observations:

  • Serialization follows specified field order, with id serialized as ID, name excluded, creattime formatted, and phone included despite being null (due to WriteMapNullValue).
  • Deserialization excludes age as configured.

JSONPath Support

FastJson version 1.2.0+ supports JSONPath for object querying.

API methods:

public class JSONPath {
    public static Object eval(Object rootObject, String path);
    public static int size(Object rootObject, String path);
    public static boolean contains(Object rootObject, String path);
    public static boolean containsValue(Object rootObject, String path, Object value);
    public static void arrayAdd(Object rootObject, String path, Object... values);
    public static boolean set(Object rootObject, String path, Object value);
}

Example usage:

String jsonStr = "{\"store\":{\"bicycle\":{\"color\":\"red\",\"price\":19.95},\"book\":[{\"author\":\"刘慈欣\",\"price\":8.95,\"category\":\"科幻\",\"title\":\"三体\"},{\"author\":\"itguang\",\"price\":12.99,\"category\":\"编程语言\",\"title\":\"go语言实战\"}]}}";
JSONObject jsonObject = JSON.parseObject(jsonStr);

List<Book> books = (List<Book>) JSONPath.eval(jsonObject, "$.store.book");
List<String> titles = (List<String>) JSONPath.eval(jsonObject, "$.store.book.title");
String title = (String) JSONPath.read(jsonStr, "$.store.book[0].title");
List<Book> filteredBooks = (List<Book>) JSONPath.read(jsonStr, "$.store.book[price > 10]");

Code Examples for Common Conversions

Array to JSON:

Integer[] intArray = new Integer[]{1, 2, 3, 4};
String json = JSON.toJSONString(intArray);
System.out.println("Serialized Array<Integer> to JSON: " + json);

List to JSON:

List<String> strList = new ArrayList<>();
strList.add("ASD14120913");
strList.add("ASD14120914");
strList.add("ASD14120915");
strList.add("ASD14120916");
String json = JSON.toJSONString(strList);
System.out.println("Serialized List to JSON: " + json);
List<String> deserializedList = (List) JSON.parseObject(json, List.class);

Set to JSON:

Set<String> strSet = new HashSet<>();
strSet.add("a");
strSet.add("b");
strSet.add("c");
strSet.add("d");
String json = JSON.toJSONString(strSet);
System.out.println("Serialized Set to JSON: " + json);
Set<String> deserializedSet = (Set) JSON.parseObject(json, Set.class);

Map to JSON:

Map<Integer, String> intStrMap = new HashMap<>();
intStrMap.put(1, "a");
intStrMap.put(2, "b");
intStrMap.put(3, "c");
intStrMap.put(4, "d");
String json = JSON.toJSONString(intStrMap);
System.out.println("Serialized Map<Integer, String>: " + json);
Map<Integer, String> deserializedMap = (Map) JSON.parseObject(json, Map.class);

Container to JSON:

List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
Set<String> set = new HashSet<>();
set.add("A");
set.add("B");
set.add("C");
set.add("D");
Map<String, Object> containerMap = new HashMap<>();
containerMap.put("one", list);
containerMap.put("two", set);
String jsonString = JSON.toJSONString(containerMap);
System.out.println("Container to JSON: " + jsonString);
Map<String, Object> deserializedContainer = JSON.parseObject(jsonString, Map.class);
Tags: fastjson

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.