FastJSON是一个高性能、功能完善的json序列化和解析工具库,可使用Maven添加依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
一、序列化
FastJSON提供了多个序列化的方法
1、基本的序列化
String json = JSON.toJSONString(Object object);
2、字符串格式化
String json = JSON.toJSONString(Object object, boolean prettyFormat); // 当prettyFormat为true
String json = JSON.toJSONString(Object object, SerializerFeature... features) // 当SerializerFeature为PrettyFormat
3、日期格式化
String json = JSON.toJSONString(new Date()); //
String json = JSON.toJSONString(new Date(), SerializerFeature.WriteDateUseDateFormat); // "2018-03-22 10:30:30"
String json = JSON.toJSONStringWithDateFormat(new Date(), "yyyy-MM-dd"); // "2018-03-22"
4、输出null字段
默认情况下,FastJSON不输出值为null的字段,可以使用SerializerFeature.WriteMapNullValue使其输出
String json = JSON.toJSONString(Object object, SerializerFeature... features) // 当SerializerFeature为WriteMapNullValue
5、数字的格式化
Map<String, Object> map = new HashMap<String, Object>();
map.put("key1", 3.3696587);
map.put("key2", "abc"); SerializeConfig serializeConfig = SerializeConfig.getGlobalInstance();
serializeConfig.put(Double.class, new DoubleSerializer("#.##"));
System.out.println(JSON.toJSONString(map)); // {"key2":"abc","key1":3.37}
6、自定义指定类型的格式化
SerializeConfig serializeConfig = new SerializeConfig();
serializeConfig.put(Double.class, new ObjectSerializer() {
@Override
public void write(JSONSerializer serializer, Object object, Object fieldName,
Type fieldType, int features) throws IOException {
serializer.out.write(String.format("%.2f", (Double)object));
}
});
System.out.println(JSON.toJSONString(map, serializeConfig)); // {"key2":"abc","key1":3.37}
详细可参考ObjectSerializer代码中的官方注释
7、自定义字段输出
保留最外层实体中为null的字段,其他字段忽略
Map<String, Object> map = new HashMap<>();
Map<String, Object> subMap = new HashMap<>();
map.put("hello", "world");
map.put("age", null);
subMap.put("aa", "123");
subMap.put("bb", null);
map.put("sub", subMap); System.out.println(JSON.toJSONString(map, new PropertyFilter() {
@Override
public boolean apply(Object object, String name, Object value) {
if (object == map || value != null) {
return true;
}
else {
return false;
}
}
}, SerializerFeature.WriteMapNullValue)); // {"sub":{"aa":"123"},"hello":"world","age":null}
详细可参考[转]FastJSON通过SerializeFilter定制序列化
二、反序列化
1、简单的反序列化
UserInfo userInfo = JSON.parseObject(json, UserInfo.class); // 实体可包含泛型字段
2、集合的反序列化
List<UserInfo> tmplist = JSON.parseArray(json, UserInfo.class);
3、泛型的反序列化
List<UserInfo> tmplist = (List<UserInfo>) JSON.parseObject(json, new TypeReference<List<UserInfo>>(){});
4、JSONObject
JSONObject实现了Map<String, Object>接口,并定义了多个获取指定类型值的方法,当不指定类型时,FastSON默认将对象的解析为JSONObject
JSONObject jsonObject = JSON.parseObject(json); // {"age":21,"name":"matt"}
System.out.println(jsonObject.getString("name"));
System.out.println(jsonObject.getInteger("age"));
json字段转换为Object对象,每种json类型均转为特定类型
String json = "[3, 3.0,\"abc\"]";
JSONArray jsonArray = JSON.parseArray(json);
for (Object obj : jsonArray) {
System.out.println(obj.getClass().getSimpleName());
}
// 输出为:Integer BigDecimal String
5、JSONArray
JSONArray实现了List<Object>接口,遍历时的对象为Object类型,使用时须强转为JSONObject类型
JSONArray jsonArray = JSON.parseArray(json); // [{"age":21,"name":"matt"},{"age":15,"name":"kevin"}]
for (Object obj : jsonArray) {
JSONObject jsonObject = (JSONObject) obj;
System.out.println(jsonObject.getString("name"));
}
6、方法参数的反序列化
对于方法的参数可能为泛型的情况,可使用parseObject(String json, Type type, Feature... features)实现反序列化
public class Company {
public void printUsers(List<UserInfo> users) {
for (UserInfo userInfo : users) {
System.out.println(String.format("name:%s, age:%d", userInfo.getName(), userInfo.getAge()));
}
}
}
String json = "[{\"name\":\"matt\",\"age\":21},{\"name\":\"kevin\",\"age\":15}]";
Method method = Company.class.getDeclaredMethods()[0];
Type type = method.getGenericParameterTypes()[0];
method.invoke(new Company(), JSON.parseObject(json, type));
// 输出:
// name:matt, age:21
// name:kevin, age:15
参考: