All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.gitee.easyopen.serializer.NullStringToEmptyAdapterFactory Maven / Gradle / Ivy

Go to download

easyopen mini版,保留基本签名校验,文档功能。https://gitee.com/durcframework/easyopen

There is a newer version: 1.0.4
Show newest version
package com.gitee.easyopen.serializer;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;

/**
 * gson null字段序列化成空字符串处理。
 * Gson gson  = new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create();
 *
 * @param 
 */
public class NullStringToEmptyAdapterFactory implements TypeAdapterFactory {

    @SuppressWarnings("unchecked")
    @Override
    public  TypeAdapter create(Gson gson, TypeToken type) {
        Class rawType = (Class) type.getRawType();
        if (rawType != String.class) {
            return null;
        }
        return (TypeAdapter) new StringNullAdapter();
    }

    public static class StringNullAdapter extends TypeAdapter {
        @Override
        public String read(JsonReader reader) throws IOException {
            if (reader.peek() == JsonToken.NULL) {
                reader.nextNull();
                return "";
            }
            return reader.nextString();
        }
        @Override
        public void write(JsonWriter writer, String value) throws IOException {
            if (value == null) {
                writer.nullValue();
                return;
            }
            writer.value(value);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy