欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

gson毛线之旅(文末提供一个封装完毕的序列化工具类)

程序员文章站 2022-03-13 12:53:05
...

什么是gson?

https://blog.csdn.net/weixin_42254857/article/details/82013895

gson的基本使用

https://blog.csdn.net/weixin_42254857/article/details/82014206

gson的常用注解

https://blog.csdn.net/weixin_42254857/article/details/82014892

gson转换使用泛型的list

https://blog.csdn.net/weixin_42254857/article/details/82015314

gson在springboot中使用时版本问题

https://blog.csdn.net/weixin_42254857/article/details/82713832

参考资料

https://www.jianshu.com/p/fc5c9cdf3aab

https://www.jianshu.com/p/e740196225a4

序列化工具类:

package com.wanma.app.util;


import com.google.gson.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

/**
 * @author xyc
 * gson util
 */
public class SerializationUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(SerializationUtil.class);

    private static final Gson GSON = new GsonBuilder().setDateFormat("yyyy/MM/dd HH:mm:ss").create();

    public static JsonObject string2JsObj(String jsonStr) {
        return GSON.fromJson(jsonStr, JsonElement.class).getAsJsonObject();
    }

    public static String gson2String(Object object) {
        return GSON.toJson(object);
    }

    /**
     * new TypeToken<Collection<Integer>>(){}.getType();
     **/
    public static <T> T gson2Object(String jsonString, Type type) {
        try {
            return GSON.fromJson(jsonString, type);
        } catch (JsonSyntaxException e) {
            LOGGER.warn("Gson string to object error, string : {} to object type {}", jsonString, type);
            throw e;
        }
    }

    public static <T> T gson2Object(String jsonString, Class<T> clazz) {
        try {
            return GSON.fromJson(jsonString, clazz);
        } catch (JsonSyntaxException e) {
            LOGGER.warn("Gson string to object error, string : {} to object type {}", jsonString, clazz.getCanonicalName());
            throw e;
        }
    }

    public static <T> List<T> gson2ObjectList(String jsonString, Class<T> clazz) {
        try {
            return GSON.fromJson(jsonString, new ParameterizedTypeImpl(clazz));
        } catch (JsonSyntaxException e) {
            LOGGER.warn("Gson string to object list error, string : {} to object type {}", jsonString, clazz.getCanonicalName());
            throw e;
        }
    }

    private static class ParameterizedTypeImpl implements ParameterizedType {
        Class clazz;

        ParameterizedTypeImpl(Class clz) {
            clazz = clz;
        }

        @Override
        public Type[] getActualTypeArguments() {
            return new Type[]{clazz};
        }

        @Override
        public Type getRawType() {
            return List.class;
        }

        @Override
        public Type getOwnerType() {
            return null;
        }
    }
}
相关标签: gson