Fastjson API示例分享

书欣 fastjson 发布时间:2022-07-23 18:06:07 阅读数:6084 1
下文笔者将使用示例分享Fastjson对API的操作示例分享,如下所示

序列化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);
}
例:
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转换为json字符串
import com.alibaba.fastjson.JSON;
Model model = ...; 
String jsonStr = JSON.toJSONString(model);
将POJO转换为json字节
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);
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/fastjson/2022/4039.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者