开发指南142-类和字符串转换

📅 发布时间:2026/7/6 0:21:51 👁️ 浏览次数:
开发指南142-类和字符串转换
这个不废话直接上代码 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 TypeReferenceResultUser() {} * T 目标泛型类型 * 反序列化后的泛型对象 */ public static T T String2Object(String json, TypeReferenceT typeReference) { // 添加常用Feature支持日期格式、允许单引号、忽略未知字段 return JSON.parseObject( json, typeReference, Feature.AllowSingleQuotes, Feature.IgnoreNotMatch ); } }一直欣赏一句话代码就是最好的文档。加好注释的代码就无需再看文档了。代码和文档合一天下无敌。