Fastjson详解
Fastjson是一個Java語言編寫的高性能功能完善的JSON庫。它采用一種“假定有序快速匹配”的算法,把JSON Parse的性能提升到極致,是目前Java語言中最快的JSON庫。Fastjson接口簡單易用,已經被廣泛使用在緩存序列化、協議交互、Web輸出、Android客戶端等多種應用場景。
主要特點:
快速FAST (比其它任何基于Java的解析器和生成器更快,包括jackson)
強大(支持普通JDK類包括任意Java Bean Class、Collection、Map、Date或enum)
零依賴(沒有依賴其它任何類庫除了JDK)
例如:
import com.alibaba.fastjson.JSON;
Group group = new Group();
group.setId(0L);
group.setName("admin");
User guestUser = new User();
guestUser.setId(2L);
guestUser.setName("guest");
User rootUser = new User();
rootUser.setId(3L);
rootUser.setName("root");
group.getUsers().add(guestUser);
group.getUsers().add(rootUser);
String jsonString = JSON.toJSONString(group);
System.out.println(jsonString);
JSON這個類是fastjson API的入口,主要的功能都通過這個類提供。
序列化API
package com.alibaba.fastjson;
public abstract class JSON {
// 將Java對象序列化為JSON字符串,支持各種各種Java基本類型和JavaBean
public static String toJSONString(Object object, SerializerFeature... features);
// 將Java對象序列化為JSON字符串,返回JSON字符串的utf-8 bytes
public static byte[] toJSONBytes(Object object, SerializerFeature... features);
// 將Java對象序列化為JSON字符串,寫入到Writer中
public static void writeJSONString(Writer writer,
Object object,
SerializerFeature... features);
// 將Java對象序列化為JSON字符串,按UTF-8編碼寫入到OutputStream中
public static final int writeJSONString(OutputStream os, //
Object object, //
SerializerFeature... features);
}
JSON字符串反序列化API
package com.alibaba.fastjson;
public abstract class JSON {
// 將JSON字符串反序列化為JavaBean
public static <T> T parseObject(String jsonStr,
Class<T> clazz,
Feature... features);
// 將JSON字符串反序列化為JavaBean
public static <T> T parseObject(byte[] jsonBytes, // UTF-8格式的JSON字符串
Class<T> clazz,
Feature... features);
// 將JSON字符串反序列化為泛型類型的JavaBean
public static <T> T parseObject(String text,
TypeReference<T> type,
Feature... features);
// 將JSON字符串反序列為JSONObject
public static JSONObject parseObject(String text);
}
接下來看:
parseTree
import com.alibaba.fastjson.*;
JSONObject jsonObj = JSON.parseObject(jsonStr);
parse pojo
import com.alibaba.fastjson.JSON;
Model model = JSON.parseObject(jsonStr, Model.class);
parse pojo generic
import com.alibaba.fastjson.JSON;
Type type = new TypeReference<List<Model>>() {}.getType();
List<Model> list = JSON.parseObject(jsonStr, type);
convert pojo to json string
import com.alibaba.fastjson.JSON;
Model model = ...;
String jsonStr = JSON.toJSONString(model);
convert pojo to json bytes
import com.alibaba.fastjson.JSON;
Model model = ...;
byte[] jsonBytes = JSON.toJSONBytes(model);
JSONField 介紹
注意:1、若屬性是私有的,必須有set*方法。否則無法反序列化。
package com.alibaba.fastjson.annotation;
public @interface JSONField {
// 配置序列化和反序列化的順序,1.1.42版本之后才支持
int ordinal() default 0;
// 指定字段的名稱
String name() default "";
// 指定字段的格式,對日期格式有用
String format() default "";
// 是否序列化
boolean serialize() default true;
// 是否反序列化
boolean deserialize() default true;
}
JSONField配置方式
FieldInfo可以配置在getter/setter方法或者字段上。例如:
配置在getter/setter上
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;}
}
配置在field上
public class A {
@JSONField(name="ID")
private int id;
public int getId() {return id;}
public void setId(int value) {this.id = id;}
}
使用format配置日期格式化
public class A {
// 配置date序列化和反序列使用yyyyMMdd日期格式
@JSONField(format="yyyyMMdd")
public Date date;
}
使用serialize/deserialize指定字段不序列化
public class A {
@JSONField(serialize=false)
public Date date;
}
public class A {
@JSONField(deserialize=false)
public Date date;
}
使用ordinal指定字段的順序
public static class VO {
@JSONField(ordinal = 3)
private int f0;
@JSONField(ordinal = 2)
private int f1;
@JSONField(ordinal = 1)
private int f2;
}
使用serializeUsing制定屬性的序列化類
public static class Model {
@JSONField(serializeUsing = ModelValueSerializer.class)
public int value;
}
public static class ModelValueSerializer implements ObjectSerializer {
@Override
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType,
int features) throws IOException {
Integer value = (Integer) object;
String text = value + "元";
serializer.write(text);
}
}
測試代碼
Model model = new Model();
model.value = 100;
String json = JSON.toJSONString(model);
Assert.assertEquals("{"value":"100元"}", json);
看一個DEMO
public static class Model {
public int id;
@JSONField(alternateNames = {"user", "person"})
public String name;
}
String jsonVal0 = "{"id":5001,"name":"Jobs"}";
String jsonVal1 = "{"id":5382,"user":"Mary"}";
String jsonVal2 = "{"id":2341,"person":"Bob"}";
Model obj0 = JSON.parseObject(jsonVal0, Model.class);
assertEquals(5001, obj0.id);
assertEquals("Jobs", obj0.name);
Model obj1 = JSON.parseObject(jsonVal1, Model.class);
assertEquals(5382, obj1.id);
assertEquals("Mary", obj1.name);
Model obj2 = JSON.parseObject(jsonVal2, Model.class);
assertEquals(2341, obj2.id);
assertEquals("Bob", obj2.name);
JSONField jsonDirect
在fastjson-1.2.12版本中,JSONField支持一個新的配置項jsonDirect,它的用途是:當你有一個字段是字符串類型,里面是json格式數據,你希望直接輸入,而不是經過轉義之后再輸出。
Model
import com.alibaba.fastjson.annotation.JSONField;
public static class Model {
public int id;
@JSONField(jsonDirect=true)
public String value;
}
Usage
Model model = new Model();
model.id = 1001;
model.value = "{}";
String json = JSON.toJSONString(model);
Assert.assertEquals("{"id":1001,"value":{}}", json);
JSONPath介紹
fastjson 1.2.0之后的版本支持JSONPath。這是一個很強大的功能,可以在java框架中當作對象查詢語言(OQL)來使用。
API:
package com.alibaba.fastjson;
public class JSONPath {
// 求值,靜態方法
public static Object eval(Object rootObject, String path);
// 計算Size,Map非空元素個數,對象非空元素個數,Collection的Size,數組的長度。其他無法求值返回-1
public static int size(Object rootObject, String path);
// 是否包含,path中是否存在對象
public static boolean contains(Object rootObject, String path) { }
// 是否包含,path中是否存在指定值,如果是集合或者數組,在集合中查找value是否存在
public static boolean containsValue(Object rootObject, String path, Object value) { }
// 修改制定路徑的值,如果修改成功,返回true,否則返回false
public static boolean set(Object rootObject, String path, Object value) {}
// 在數組或者集合中添加元素
public static boolean array_add(Object rootObject, String path, Object... values);
}
建議緩存JSONPath對象,這樣能夠提高求值的性能
支持語法
| JSONPATH | 描述 |
| $ | 根對象,例如$.name |
| [num] | 數組訪問,其中num是數字,可以是負數。例如$[0].leader.departments[-1].name |
| [num0,num1,num2...] | 數組多個元素訪問,其中num是數字,可以是負數,返回數組中的多個元素。例如$[0,3,-2,5] |
| [start:end] | 數組范圍訪問,其中start和end是開始小表和結束下標,可以是負數,返回數組中的多個元素。例如$[0:5] |
| [start:end :step] | 數組范圍訪問,其中start和end是開始小表和結束下標,可以是負數;step是步長,返回數組中的多個元素。例如$[0:5:2] |
| [?(key)] | 對象屬性非空過濾,例如$.departs[?(name)] |
| [key > 123] | 數值類型對象屬性比較過濾,例如$.departs[id >= 123],比較操作符支持=,!=,>,>=,<,<= |
| [key = '123'] | 字符串類型對象屬性比較過濾,例如$.departs[name = '123'],比較操作符支持=,!=,>,>=,<,<= |
| [key like 'aa%'] | 字符串類型like過濾, 例如$.departs[name like 'sz*'],通配符只支持% 支持not like |
| [key rlike 'regexpr'] | 字符串類型正則匹配過濾, 例如departs[name like 'aa(.)*'], 正則語法為jdk的正則語法,支持not rlike |
| [key in ('v0', 'v1')] | IN過濾, 支持字符串和數值類型 例如: $.departs[name in ('wenshao','Yako')] $.departs[id not in (101,102)] |
| [key between 234 and 456] | BETWEEN過濾, 支持數值類型,支持not between 例如: $.departs[id between 101 and 201] $.departs[id not between 101 and 201] |
| length() 或者 size() | 數組長度。例如$.values.size() 支持類型java.util.Map和java.util.Collection和數組 |
| . | 屬性訪問,例如$.name |
| .. | deepScan屬性訪問,例如$..name |
| * | 對象的所有屬性,例如$.leader.* |
| ['key'] | 屬性訪問。例如$['name'] |
| ['key0','key1'] | 多個屬性訪問。例如$['id','name'] |
以下兩種寫法的語義是相同的:
$.store.book[0].title
$['store']['book'][0]['title']
語法示例
| JSONPath | 語義 |
| $ | 根對象 |
| $[-1] | 最后元素 |
| $[:-2] | 第1個至倒數第2個 |
| $[1:] | 第2個之后所有元素 |
| $[1,2,3] |
集合中1,2,3個元素 |
API 示例
public void test_entity() throws Exception {
Entity entity = new Entity(123, new Object());
Assert.assertSame(entity.getValue(), JSONPath.eval(entity, "$.value"));
Assert.assertTrue(JSONPath.contains(entity, "$.value"));
Assert.assertTrue(JSONPath.containsValue(entity, "$.id", 123));
Assert.assertTrue(JSONPath.containsValue(entity, "$.value", entity.getValue()));
Assert.assertEquals(2, JSONPath.size(entity, "$"));
Assert.assertEquals(0, JSONPath.size(new Object[], "$"));
}
public static class Entity {
private Integer id;
private String name;
private Object value;
public Entity() {}
public Entity(Integer id, Object value) { this.id = id; this.value = value; }
public Entity(Integer id, String name) { this.id = id; this.name = name; }
public Entity(String name) { this.name = name; }
public Integer getId() { return id; }
public Object getValue() { return value; }
public String getName() { return name; }
public void setId(Integer id) { this.id = id; }
public void setName(String name) { this.name = name; }
public void setValue(Object value) { this.value = value; }
}
讀取集合多個元素的某個屬性
List<Entity> entities = new ArrayList<Entity>();
entities.add(new Entity("wenshao"));
entities.add(new Entity("ljw2083"));
List<String> names = (List<String>)JSONPath.eval(entities, "$.name"); // 返回enties的所有名稱
Assert.assertSame(entities.get(0).getName(), names.get(0));
Assert.assertSame(entities.get(1).getName(), names.get(1));
返回集合中多個元素
List<Entity> entities = new ArrayList<Entity>();
entities.add(new Entity("wenshao"));
entities.add(new Entity("ljw2083"));
entities.add(new Entity("Yako"));
List<Entity> result = (List<Entity>)JSONPath.eval(entities, "[1,2]"); // 返回下標為1和2的元素
Assert.assertEquals(2, result.size());
Assert.assertSame(entities.get(1), result.get(0));
Assert.assertSame(entities.get(2), result.get(1));
按范圍返回集合的子集
List<Entity> entities = new ArrayList<Entity>();
entities.add(new Entity("wenshao"));
entities.add(new Entity("ljw2083"));
entities.add(new Entity("Yako"));
List<Entity> result = (List<Entity>)JSONPath.eval(entities, "[0:2]"); // 返回下標從0到2的元素
Assert.assertEquals(3, result.size());
Assert.assertSame(entities.get(0), result.get(0));
Assert.assertSame(entities.get(1), result.get(1));
Assert.assertSame(entities.get(2), result.get(1));
通過條件過濾,返回集合的子集
List<Entity> entities = new ArrayList<Entity>();
entities.add(new Entity(1001, "ljw2083"));
entities.add(new Entity(1002, "wenshao"));
entities.add(new Entity(1003, "yakolee"));
entities.add(new Entity(1004, null));
List<Object> result = (List<Object>) JSONPath.eval(entities, "[id in (1001)]");
Assert.assertEquals(1, result.size());
Assert.assertSame(entities.get(0), result.get(0));
根據屬性值過濾條件判斷是否返回對象,修改對象,數組屬性添加元素
Entity entity = new Entity(1001, "ljw2083");
Assert.assertSame(entity , JSONPath.eval(entity, "[id = 1001]"));
Assert.assertNull(JSONPath.eval(entity, "[id = 1002]"));
JSONPath.set(entity, "id", 123456); //將id字段修改為123456
Assert.assertEquals(123456, entity.getId().intValue());
JSONPath.set(entity, "value", new int[0]); //將value字段賦值為長度為0的數組
JSONPath.arrayAdd(entity, "value", 1, 2, 3); //將value字段的數組添加元素1,2,3
接下來看:
Map root = Collections.singletonMap("company", //
Collections.singletonMap("departs", //
Arrays.asList( //
Collections.singletonMap("id",
1001), //
Collections.singletonMap("id",
1002), //
Collections.singletonMap("id", 1003) //
) //
));
List<Object> ids = (List<Object>) JSONPath.eval(root, "$..id");
assertEquals(3, ids.size());
assertEquals(1001, ids.get(0));
assertEquals(1002, ids.get(1));
assertEquals(1003, ids.get(2));
以上就暫時介紹這么多了。下次有時間在整理吧。
有問題可以在下面評論,技術問題可以私聊我。
總結
以上是生活随笔為你收集整理的Fastjson详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android中形状图形 | shape
- 下一篇: 虚拟机中安装GHO文件配置说明