com.gitee.easyopen.serializer.NullStringToEmptyAdapterFactory Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of easyopen-mini Show documentation
Show all versions of easyopen-mini Show documentation
easyopen mini版,保留基本签名校验,文档功能。https://gitee.com/durcframework/easyopen
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);
}
}
}