Skip to content
This repository was archived by the owner on Jul 29, 2026. It is now read-only.

JSON_API_cn

wenshao edited this page May 15, 2016 · 7 revisions

JSON这个类是fastjson API的入口,主要的功能都通过这个类提供。

序列化API

packagecom.alibaba.fastjson;
publicabstractclassJSON {
// 将Java对象序列化为JSON字符串,支持各种各种Java基本类型和JavaBeanpublicstaticStringtoJSONString(Objectobject, SerializerFeature... features);
// 将Java对象序列化为JSON字符串,返回JSON字符串的utf-8 bytespublicstaticbyte[] toJSONBytes(Objectobject, SerializerFeature... features);
// 将Java对象序列化为JSON字符串,写入到Writer中publicstaticvoidwriteJSONString(Writerwriter, Objectobject, SerializerFeature... features);
// 将Java对象序列化为JSON字符串,按UTF-8编码写入到OutputStream中publicstaticfinalintwriteJSONString(OutputStreamos, // Objectobject, // SerializerFeature... features);
}

JSON字符串反序列化API

packagecom.alibaba.fastjson;
publicabstractclassJSON {
// 将JSON字符串反序列化为JavaBeanpublicstatic <T> TparseObject(StringjsonStr, Class<T> clazz, Feature... features);
// 将JSON字符串反序列化为JavaBeanpublicstatic <T> TparseObject(byte[] jsonBytes, // UTF-8格式的JSON字符串Class<T> clazz, Feature... features);
// 将JSON字符串反序列化为泛型类型的JavaBeanpublicstatic <T> TparseObject(Stringtext, TypeReference<T> type, Feature... features);
// 将JSON字符串反序列为JSONObjectpublicstaticJSONObjectparseObject(Stringtext);
}

Demo

parse Tree

importcom.alibaba.fastjson.*;
JSONObjectjsonObj = JSON.parseObject(jsonStr);

parse POJO

importcom.alibaba.fastjson.JSON;
Modelmodel = JSON.parseObject(jsonStr, Model.class);

parse POJO Generic

importcom.alibaba.fastjson.JSON;
Typetype = newTypeReference<List<Model>>() {}.getType(); List<Model> list = JSON.parseObject(jsonStr, type);

convert POJO to json string

importcom.alibaba.fastjson.JSON;
Modelmodel = ...; StringjsonStr = JSON.toJSONString(model);

convert POJO to json bytes

importcom.alibaba.fastjson.JSON;
Modelmodel = ...; byte[] jsonBytes = JSON.toJSONBytes(model);

write POJO as json string to OutputStream

importcom.alibaba.fastjson.JSON;
Modelmodel = ...; OutputStreamos;
JSON.writeJSONString(os, model);

write POJO as json string to Writer

importcom.alibaba.fastjson.JSON;
Modelmodel = ...; Writerwriter = ...;
JSON.writeJSONString(writer, model);

Clone this wiki locally