gson序列化对象(值为空也序列化、值为null转换为""、排除策略)

修改记录

日期提出说明
2018-03-23 20:08@bxl049AnnotationExclusion、FieldExclusion这两哥类代码也没有贴呀
2018-01-03 17:24@xianglin007你这个只能将String类型的null转为空字符串啊,如果是Int、Long、ArrayList呢?那岂不是要写全部的数据类型,如果不管是什么类型都转换为空字符串,这个就不行了,比如Int类型的null只能转为Int不能转为空字符串。

gson序列化对象

/**
*YC 
*2017年8月1日 下午4:59:14
* <p>Description: </p> 
*/
package com.huiw.core.uic.common.utils.gson;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.huiw.core.uic.common.adapter.NullStringToEmptyAdapterFactory;
import com.huiw.core.uic.common.utils.converter.AnnotationExclusion;
import com.huiw.core.uic.common.utils.converter.FieldExclusion;

/**
 * @author YC 获取一个完美gson:
 * 
 */
public class PerfectGson {
    /**
     * 
     * YC 2017年8月1日 下午5:09:34
     * <p>
     * Title: getGson
     * </p>
     * <p>
     * Description:
     * <h1>完美gson具有如下功能:</h1>
     * <p>
     * 1、serializeNulls(值为空也序列化)
     * </p>
     * <p>
     * 2、registerTypeAdapterFactory(new
     * NullStringToEmptyAdapterFactory())(值为null转换为"")
     * </p>
     * <p>
     * 3、.setExclusionStrategies(new TargetStrategy())(排除策略 )
     * </p>
     * 
     * @return
     */
    public static Gson getGson() {
        return new GsonBuilder().serializeNulls()
                .registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory<Object>())
                .setExclusionStrategies(new AnnotationExclusion()).create();
    }

    /**
     * 
     * YC 2017年8月11日 下午2:39:33
     * <p>
     * Title: getGson
     * </p>
     * <p>
     * Description: 带参
     * </p>
     * 
     * @param strs
     * @return
     */
    public static Gson getGson(String[] strs) {
        return new GsonBuilder().serializeNulls()
                .registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory<Object>())
                .setExclusionStrategies(new FieldExclusion(strs)).create();
    }
}

AnnotationExclusion类

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.huiw.archives.common.annotation.MyExclus;

/**
 * YC 2017年8月1日 下午2:39:22
 * <p>
 * Title:排除策略
 * </p>
 * <p>
 * Description: 用于排除一个类不用转换的字段
 * </p>
 */
public class AnnotationExclusion implements ExclusionStrategy {

    /**
     * 
     * YC 2017年8月1日 下午2:41:39
     * <p>
     * Title: shouldSkipClass
     * </p>
     * <p>
     * Description: 应该排除的类
     * </p>
     * 
     * @param class1
     * @return
     * @see com.google.gson.ExclusionStrategy#shouldSkipClass(java.lang.Class)
     */
    @Override
    public boolean shouldSkipClass(Class<?> class1) {
        return false;
    }

    /**
     * 
     * YC 2017年8月1日 下午2:41:57
     * <p>
     * Title: shouldSkipField
     * </p>
     * <p>
     * Description: 应该排除的字段
     * </p>
     * 
     * @param fieldattributes
     * @return
     * @see com.google.gson.ExclusionStrategy#shouldSkipField(com.google.gson.FieldAttributes)
     */
    @Override
    public boolean shouldSkipField(FieldAttributes f) {
         //如果属性带有MyExclus 注解,则排除
        return f.getAnnotation(MyExclus.class) != null;
    }

}

FieldExclusion类

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.huiw.archives.common.annotation.MyExclus;

/**
 * YC 2017年8月1日 下午2:39:22
 * <p>
 * Title:手动字段排除策略
 * </p>
 * <p>
 * Description: 用于排除一个类不用转换的字段
 * </p>
 */
public class FieldExclusion implements ExclusionStrategy {
    String[] inStr;

    public FieldExclusion(String[] outStr) {
        this.inStr = outStr;
    }

    /**
     * 
     * YC 2017年8月1日 下午2:41:39
     * <p>
     * Title: shouldSkipClass
     * </p>
     * <p>
     * Description: 应该排除的类
     * </p>
     * 
     * @param class1
     * @return
     * @see com.google.gson.ExclusionStrategy#shouldSkipClass(java.lang.Class)
     */
    @Override
    public boolean shouldSkipClass(Class<?> class1) {
        return false;
    }

    /**
     * 
     * YC 2017年8月1日 下午2:41:57
     * <p>
     * Title: shouldSkipField
     * </p>
     * <p>
     * Description: 应该排除的字段
     * </p>
     * 
     * @param fieldattributes
     * @return
     * @see com.google.gson.ExclusionStrategy#shouldSkipField(com.google.gson.FieldAttributes)
     */
    @Override
    public boolean shouldSkipField(FieldAttributes f) {
        boolean flag = false;

        for (int i = 0; i < inStr.length; i++) {
            // 手动排除inStr串指定字段
            if (f.getName().equals(inStr[i])) {
                flag = true;
                System.out.println("排除字段===============>" + f.getName());
            } else {
                // 如果属性带有MyExclus 注解,则排除
                flag = f.getAnnotation(MyExclus.class) != null;
            }
        }

        return flag;
    }

}

MyExclus接口

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author YC 如果属性带有MyExclus 注解,则GSON转换时排除
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD })
public @interface MyExclus {

}

值为空也序列化

public static Gson getGson(String[] strs) {
        return new GsonBuilder().serializeNulls().create();
}

值为null转换为”“

public static Gson getGson(String[] strs) {
        return new GsonBuilder()
                .registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory<Object>())
                .create();
}

/**
*YC 
*2017年8月1日 下午4:41:21
* <p>Description: </p> 
*/
package com.huiw.core.uic.common.adapter;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;

/**
 * @author YC 将null转换为""工厂适配器
 */
public class NullStringToEmptyAdapterFactory<T> implements TypeAdapterFactory {
    @SuppressWarnings({ "unchecked", "hiding" })
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
        Class<T> rawType = (Class<T>) type.getRawType();
        if (rawType != String.class) {
            return null;
        }
        return (TypeAdapter<T>) new StringNullAdapter();
    }
}

/**
*YC 
*2017年8月1日 下午4:36:50
* <p>Description: </p> 
*/
package com.huiw.core.uic.common.adapter;

import java.io.IOException;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

/**
 * @author YC 将null转换为""适配器
 */
public class StringNullAdapter extends TypeAdapter<String> {
    @Override
    public String read(JsonReader reader) throws IOException {
        // TODO Auto-generated method stub
        if (reader.peek() == JsonToken.NULL) {
            reader.nextNull();
            return "";
        }
        return reader.nextString();
    }

    @Override
    public void write(JsonWriter writer, String value) throws IOException {
        // TODO Auto-generated method stub
        if (value == null) {
            writer.nullValue();
            return;
        }
        writer.value(value);
    }

}

排除策略

public static Gson getGson() {
        return new GsonBuilder().setExclusionStrategies(new AnnotationExclusion()).create();
}

@你这个只能将String类型的null转为空字符串啊,如果是Int、Long、ArrayList呢?那岂不是要写全部的数据类型,如果不管是什么类型都转换为空字符串,这个就不行了,比如Int类型的null只能转为Int不能转为空字符串。

public class Person implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private String name;
    private Integer age;
    //User类似Person对象有name、age字段
    private List<User> list;
        //set、get略
}

public static void main(String[] args) {
        // 获取PerfectGson对象
        Gson gson = PerfectGson.getGson();
        // 实例化一个人(name[String]、age[Intager]、list[List<User>]),未赋值
        Person person = new Person();
        // PerfectGson转换出一个值为空的json串
        gson = gson.fromJson(gson.toJson(person), new TypeToken<Person>() {
        }.getType());
        // 模拟spring MVC的controller层返回给ajax的数据
        System.out.println(JSONObject.fromObject(gson));
    }

//控制台:
//{"name":"","age":0,"list":[]}
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

技术杨工

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值