Alibaba fastjson 序列化与反序列化
fastjson
FASTJSON 2.0.x has been released, faster and more secure, recommend you upgrade.
项目地址:https://gitcode.com/gh_mirrors/fastj/fastjson
·
fastjson在官网的定义号称最小最快 多态的json序列化工具。fastjson采用独创的算法,将parse的速度提升到极致,超过所有json库,包括曾经号称最快的jackson。并且还超越了google的二进制协议protocol buf。
JSON这个类是fastjson 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
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的知识可以去w3c去了解:https://www.w3cschool.cn/fastjson/
FASTJSON 2.0.x has been released, faster and more secure, recommend you upgrade.
最近提交(Master分支:4 个月前 )
c942c834 - 2 年前
5bc4709b - 2 年前
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐


所有评论(0)