Introduction to Fastjson

Introduction

Fastjson is a high-performance JSON library written in Java language.

high performance

fastjson adopts an original algorithm to increase the speed of parse to the extreme, surpassing all json libraries, including jackson, which was once known as the fastest. And it also surpasses Google's binary protocol protocol buf.

support standard

  • Fastjson fully supports the http://json.org standard, and is also one of the reference implementations included in the official website.

Powerful

  • Various JDK types are supported. Including basic types, JavaBean, Collection, Map, Enum, generics, etc.
  • Supports circular references

no dependencies

  • No need for extra jars, it can run directly on the JDK.

Wide range of support

  • Support JDK 5, JDK 6, Android, Aliyun mobile phone and other environments.

open source

fully tested

  • fastjson has more than 1,500 testcases, which will be run every time it is built. Rich test scenarios ensure stable functions.

get fastjson

download

http://code.alibabatech.com/mvn/releases/com/alibaba/fastjson/

maven

If you use Maven, the maven repository configuration is as follows:

<repository>
     <id>opensesame</id>
     <name>Alibaba OpenSource Repsoitory</name>
     <url>http: //code.alibabatech.com/mvn/releases/</url>
     <snapshots>
         <enabled> false </enabled>
     </snapshots>
</repository>

Add dependencies to the pom.xml file:

<dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>fastjson</artifactId>
     <version> 1.1 . 23 </version>
</dependency>

Serialization

The most basic functions involved in a JSON library are serialization and deserialization. Fastjson supports direct serialization of java beans. You can use the com.alibaba.fastjson.JSON class for serialization and deserialization.

basic serialization

Serialization is to convert JavaBean objects into text in JSON format.

Object o = ...;
String text = JSON.toJSONString(o);

In this example, the JSON.toJSONString method is called to convert the object o into JSON-formatted text.

use single quotes

标准的JSON是使用双引号的,javascript支持使用单引号格式的json文本,fastjson也支持这个特性,打开SerializerFeature.UseSingleQuotes这个特性就可以了了,例如:

Object o = ...;
String text = JSON.toJSONString(o, SerializerFeature.UseSingleQuotes);

fastjson序列化时可以选择的SerializerFeature有十几个,你可以按照自己的需要去选择使用。

日期格式化

fastjson直接支持日期类型数据的格式化,包括java.util.Date、java.sql.Date、java.sql.Timestamp、java.sql.Time。

缺省情况下,fastjson将Date类型序列化为long,这个使得序列化和反序列化的过程不会导致时区问题。如:
例如:

long millis = 1324138987429L;
Date date = new Date(millis);       
System.out.println(JSON.toJSONString(date));

输出的结果是

1324138987429

fastjson还提供了基于格式化输出的SerializerFeature,例如:

JSON.toJSONString(date, SerializerFeature.WriteDateUseDateFormat);

输出的结果为:

"2011-12-18 00:23:07"

你可以指定输出日期的格式,比如修改为输出毫秒:

JSON.toJSONStringWithDateFormat(date, "yyyy-MM-dd HH:mm:ss.SSS" );

输出的结果为:

"2011-12-18 00:23:07.429"

使用WriteClassName特性

fastjson支持序列化时写入类型信息,从而使得反序列化时不至于类型信息丢失。例如:

Color color = Color.RED;
String text = JSON.toJSONString(color, SerializerFeature.WriteClassName);
System.out.println(text);

输出结果:

{ "@type" : "java.awt.Color" , "r" : 255 , "g" : 0 , "b" : 0 , "alpha" : 255 }

由于序列化带了类型信息,使得反序列化时能够自动进行类型识别,例如:

String text = ...; // {"@type":"java.awt.Color","r":255,"g":0,"b":0,"alpha":255}
Color color = (Color) JSON.parse(text);

浏览器和设备兼容

fastjson缺省的序列化内容,是对序列化结果紧凑做了优化配置,使得序列化之后长度更小,但是这种优化配置是对一些浏览器和设备不兼容的。比如说在iphone上兼容emoji(绘文字)。

JSON.toJSONString(o, SerializerFeature.BrowserCompatible);

循环引用

很多场景中,我们需要序列化的对象中存在循环引用,在许多的json库中,这会导致stackoverflow。在功能强大的fastjson中,你不需要担心这个问题。例如:

A a = new A();
B b = new B(a);
a.setB(b);
 
String text = JSON.toJSONString(a); // {"b":{"a":{"$ref":".."}}}
A a1 = JSON.parseObject(text, A. class );
Assert.assertTrue(a1 == a1.getB().getA());

引用是通过"$ref"来表示的

引用 描述
"$ref":".." 上一级
"$ref":"@" 当前对象,也就是自引用
"$ref":"$" root object
"$ref":"$.children.0" Path-based references, equivalent to root.getChildren().get(0)

Use @JSONField Annotation

In some scenarios, you may need to customize the serialization output. For example, if you want to use "ID" instead of "id" after serialization, you can use @JSONField this Annotation.

public class User {
     @JSONField (name= "ID" )
     public int getId() { ... }
}
 
User user = ...;
JSON.toJSONString(user); // {"ID":234}

Upgrade from json-lib

If you have used json-lib and hate its snail-like speed and wordy API, it is recommended that you upgrade to fastjson, which is fully compatible with the serialization format of json-lib.

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.JSONLibDataFormatSerializer;
import com.alibaba.fastjson.serializer.JSONSerializerMap;
import com.alibaba.fastjson.serializer.SerializerFeature;
  
private static final SerializeConfig   config;
static {
     config = new SerializeConfig();
     config.put(java.util.Date. class , new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式
     config.put(java.sql.Date. class , new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式
}
  
private static final SerializerFeature[] features = { SerializerFeature.WriteMapNullValue, // 输出空置字段
         SerializerFeature.WriteNullListAsEmpty, // list字段如果为null,输出为[],而不是null
         SerializerFeature.WriteNullNumberAsZero, // 数值字段如果为null,输出为0,而不是null
         SerializerFeature.WriteNullBooleanAsFalse, // Boolean字段如果为null,输出为false,而不是null
         SerializerFeature.WriteNullStringAsEmpty // 字符类型字段如果为null,输出为"",而不是null
                                                   };
  
// 序列化为和JSON-LIB兼容的字符串
public static String toCompatibleJSONString(Object object) {
     return JSON.toJSONString(object, config, features);
}

Through the toCompatibleJSONString method in the above code, you can achieve full compatibility with json-lib.

deserialization

Deserialization is to convert text in JSON format into Java Bean objects.

Specify Class information deserialization

By specifying type information, it is very convenient to deserialize "JSON text" into "Java Bean" object, for example:

String text = ...; // {"r":255,"g":0,"b":0,"alpha":255}
Color color = JSON.parseObject(text, Color. class );

Deserialization of collections of types

This interface is similar to parseObject

String text = ...; // [{ ... }, { ... }]
List<User> users = JSON.parseArray(text, User. class );

Generic deserialization

If you need to return an object with a generic type, such as List<User>, Map<String, User>, you can use TypeReference to pass in type information.

String text = ...; // {"name":{"name":"ljw",age:18}}
Map<String, User> userMap = JSON.parseObject(text, new TypeReference<Map<String, User>>() {});

Deserialization of collections of composite types

For example, in network protocols, there are often such combinations:

[{ /*header*/}, {/*body*/ }]

fastjson has dedicated support for deserialization of such structures.

String text = ...; // [{/* header */}, {/* body */}]
Type[] types = new Type[] {Header. class , Body. class };
List<Object> list = JSON.parseArray(text, types);
Header header = (Header) list.get( 0 );
Body body = (Body) list.get( 1 );

Use @JSONCreator to specify the constructor to create the object

If your JavaBean does not have a default constructor, you can use @JSONCreator to specify the constructor

public static class Entity {
     private final int    id;
     private final String name;
 
     @JSONCreator
     public Entity( @JSONField (name = "id" ) int id, @JSONField (name = "name" ) String name){
         this .id = id;
         this .name = name;
     }
 
     public int getId() { return id; }
     public String getName() { return name; }
}

Deserialize JSON text into a prototype interface

public static interface Bean {
     int getId();
 
     void setId( int value);
 
     String getName();
 
     void setName(String value);
}
 
String text = "{\"id\":123, \"name\":\"chris\"}" ;
Bean bean = JSON.parseObject(text, Bean. class );
 
// 按接口调用
Assert.assertEquals( 123 , bean.getId());
Assert.assertEquals( "chris" , bean.getName());
bean.setId( 234 );
Assert.assertEquals( 234 , bean.getId());

Guess you like

Origin blog.csdn.net/MingDaw/article/details/8098948
Recommended