这个不废话,直接上代码:
package org.qlm.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
public class Object2JsonUtil {
public static String object2String(Object o) {
String featureJson = JSON.toJSONString(
o,
SerializerFeature.PrettyFormat, // 美化输出(1.2.83的特性名和2.x略有差异)
SerializerFeature.WriteMapNullValue, // 输出null字段
SerializerFeature.WriteDateUseDateFormat // 日期转字符串(默认格式yyyy-MM-dd HH:mm:ss)
);
return featureJson;
}
/**
* 通用泛型反序列化工具方法(Fastjson 1.2.83)
* json JSON字符串
* typeReference 泛型类型引用(如new TypeReference<Result<User>>() {})
* <T> 目标泛型类型
* 反序列化后的泛型对象
*/
public static <T> T String2Object(String json, TypeReference<T> typeReference) {
// 添加常用Feature:支持日期格式、允许单引号、忽略未知字段
return JSON.parseObject(
json,
typeReference,
Feature.AllowSingleQuotes,
Feature.IgnoreNotMatch
);
}
}
一直欣赏一句话,代码就是最好的文档。加好注释的代码,就无需再看文档了。代码和文档合一,天下无敌。