JSON這個(gè)類是fastjson API的入口,主要的功能都通過這個(gè)類提供。
package com.alibaba.fastjson;
public abstract class JSON {
// 將Java對(duì)象序列化為JSON字符串,支持各種各種Java基本類型和JavaBean
public static String toJSONString(Object object, SerializerFeature... features);
// 將Java對(duì)象序列化為JSON字符串,返回JSON字符串的utf-8 bytes
public static byte[] toJSONBytes(Object object, SerializerFeature... features);
// 將Java對(duì)象序列化為JSON字符串,寫入到Writer中
public static void writeJSONString(Writer writer,
Object object,
SerializerFeature... features);
// 將Java對(duì)象序列化為JSON字符串,按UTF-8編碼寫入到OutputStream中
public static final int writeJSONString(OutputStream os,
Object object,
SerializerFeature... features);
}
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);
}
import com.alibaba.fastjson.*;
JSONObject jsonObj = JSON.parseObject(jsonStr);
import com.alibaba.fastjson.JSON;
Model model = JSON.parseObject(jsonStr, Model.class);
解析POJO泛型
import com.alibaba.fastjson.JSON;
Type type = new TypeReference<List<Model>>() {}.getType();
List<Model> list = JSON.parseObject(jsonStr, type);
將POJO轉(zhuǎn)換為json字符串
import com.alibaba.fastjson.JSON;
Model model = ...;
String jsonStr = JSON.toJSONString(model);
將POJO轉(zhuǎn)換為json字節(jié)
import com.alibaba.fastjson.JSON;
Model model = ...;
byte[] jsonBytes = JSON.toJSONBytes(model);
將POJO作為json字符串寫入OutputStream
import com.alibaba.fastjson.JSON;
Model model = ...;
OutputStream os;
JSON.writeJSONString(os, model);
將POJO作為json字符串寫入Writer
import com.alibaba.fastjson.JSON;
Model model = ...;
Writer writer = ...;
JSON.writeJSONString(writer, model);
更多建議: