Gson 转json时字段没有值,json就没有该字段和替换字符串字段的值为null
程序员文章站
2024-03-16 09:49:40
...
Gson 类转json字符串时,有些字段没值,那么这个字段就在json里没有添加serializeNulls()方法即可例如:
Gson gson=new GsonBuilder().setDateFormat(DateFormat.SECOND_FIELD).serializeNulls().create();
当然没有值得字段回显示null,所以自定义一下NullStringToEmptyAdapterFactory例如:
GsonBuilder gb = new GsonBuilder().setDateFormat(DateFormat.SECOND_FIELD).serializeNulls()
.registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory<>());
Gson gson = gb.create();
class NullStringToEmptyAdapterFactory<T> implements TypeAdapterFactory {
@SuppressWarnings({ "hiding", "unchecked" })
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();
}
}
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.value("");
return;
}
writer.value(value);
}