Fastjson API中文版

2022-05-05 15:38 更新

JSON這個(gè)類是fastjson API的入口,主要的功能都通過這個(gè)類提供。

序列化API

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);
}

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);

解析POJO

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);


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)