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);
}
Demo
parse Tree
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);
write POJO as json string to OutputStream
import com.alibaba.fastjson.JSON;
Model model = ...;
OutputStream os;
JSON.writeJSONString(os, model);
write POJO as json string to Writer
import com.alibaba.fastjson.JSON;
Model model = ...;
Writer writer = ...;
JSON.writeJSONString(writer, model);
Fastjson JSONField
1. 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;
}
2. JSONField配置方式
JSONField可以配置在getter/setter方法或者字段上。例如:
2.1 配置在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;}
}
2.2 配置在field上
public class A {
@JSONField(name="ID")
private int id;
public int getId() {return id;}
public void setId(int value) {this.id = id;}
}
3. 使用format配置日期格式化
public class A {
// 配置date序列化和反序列使用yyyyMMdd日期格式
@JSONField(format="yyyyMMdd")
public Date date;
}
4. 使用serialize/deserialize指定字段不序列化
public class A {
@JSONField(serialize=false)
public Date date;
}
public class A {
@JSONField(deserialize=false)
public Date date;
}
5. 使用ordinal指定字段的顺序
缺省fastjson序列化一个java bean,是根据fieldName的字母序进行序列化的,你可以通过ordinal指定字段的顺序。这个特性需要1.1.42以上版本。
public static class VO {
@JSONField(ordinal = 3)
private int f0;
@JSONField(ordinal = 2)
private int f1;
@JSONField(ordinal = 1)
private int f2;
}
6. 使用serializeUsing制定属性的序列化类
在fastjson 1.2.16版本之后,JSONField支持新的定制化配置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);
7、JSONField alternateNames
在fastjson在1.2.21版本中提供了一个借鉴自gson的特性,支持反序列化时使用多个不同的字段名称,使用的方式是配置JSONField的alternateNames。
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);
8、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);