GSON 序列化工具类

  1. 序列化 thrift 对象时,能够移除一些无效字段
public class GsonUtils {
    private final static List<String> shouldSkipList = new ArrayList<>();

    //序列化 thrift 对象成 字符串时, 避免一些无效的字段
    static {
        shouldSkipList.add("__isset_bit_vector");
        shouldSkipList.add("optionals");
    }

    private static Gson DEFAULT_GSON = new GsonBuilder().create();

    public static Gson GSON_LOWER_CASE_UNDERSCORES = new GsonBuilder()
            .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .create();

    public static Gson GSON_SKIP = new GsonBuilder().addSerializationExclusionStrategy(new ExclusionStrategy() {
        @Override
        public boolean shouldSkipField(FieldAttributes f) {
            return shouldSkipList.contains(f.getName());
        }

        @Override
        public boolean shouldSkipClass(Class<?> aClass) {
            return false;
        }
    }).create();

    public static  <T> T fromJson(String json, Class<T> classOfT) throws JsonSyntaxException {
        return DEFAULT_GSON.fromJson(json, classOfT);
    }

    public static  <T> T fromJson(String json, Type typeOfT) throws JsonSyntaxException {
        return DEFAULT_GSON.fromJson(json, typeOfT);
    }

    public static String toJson(Object src) {
        return DEFAULT_GSON.toJson(src);
    }

    public static String toJsonSkipFields(Object src) {
        return GSON_SKIP.toJson(src);
    }
}
posted @ 2024-04-03 16:43  大熊猫同学  阅读(39)  评论(0)    收藏  举报