是否有通用的方法告诉Gson不写空字符串?
我强烈不喜欢必须实现一个处理每个字段的TypeAdapter,因为answer here有点暗示。
答案 0 :(得分:3)
排序。据我所知,Gson不允许你对对象字段进行太多控制,唯一的控件就知道你可以拥有它@JsonAdapter
。例如,
import com.google.gson.annotations.JsonAdapter;
final class Pack {
@JsonAdapter(EmptyStringTypeAdapter.class)
final String foo;
@JsonAdapter(EmptyStringTypeAdapter.class)
final String bar;
private Pack(final String foo, final String bar) {
this.foo = foo;
this.bar = bar;
}
static Pack of(final String foo, final String bar) {
return new Pack(foo, bar);
}
@Override
public String toString() {
return foo + " " + bar;
}
}
尽管对某人来说可能看起来很乏味,但它可以让您完全控制数据传输对象,让您可以选择如何处理此字符串或该字符串。示例类型适配器可能如下:
final class EmptyStringTypeAdapter
extends TypeAdapter<String> {
private EmptyStringTypeAdapter() {
}
@Override
@SuppressWarnings("resource")
public void write(final JsonWriter jsonWriter, @Nullable final String s)
throws IOException {
if ( s == null || s.isEmpty() ) {
jsonWriter.nullValue();
} else {
jsonWriter.value(s);
}
}
@Override
@Nonnull
@SuppressWarnings("EnumSwitchStatementWhichMissesCases")
public String read(final JsonReader jsonReader)
throws IOException {
final JsonToken token = jsonReader.peek();
switch ( token ) {
case NULL:
return "";
case STRING:
return jsonReader.nextString();
default:
throw new IllegalStateException("Unexpected token: " + token);
}
}
}
有一点需要注意的是,它无法从空值中恢复空字符串(不幸的是,您在此处遇到了不可逆转的转换),因此您可能还需要查看https://github.com/google/gson/blob/master/extras/src/main/java/com/google/gson/typeadapters/PostConstructAdapterFactory.java以恢复@JsonAdapter(EmptyStringTypeAdapter.class)
读取的注释字段。示例测试:
private static final Gson gson = new Gson();
private static final Type listOfStringType = new TypeToken<List<String>>() {
}.getType();
public static void main(final String... args) {
// Single elements
ImmutableList.of(Pack.of("", ""), Pack.of("foo", ""), Pack.of("", "bar"), Pack.of("foo", "bar"))
.stream()
.peek(pack -> System.out.println("Pack before: " + pack))
.map(gson::toJson)
.peek(json -> System.out.println("JSON: " + json))
.map(json -> gson.fromJson(json, Pack.class))
.peek(pack -> System.out.println("Pack after: " + pack))
.forEach(pack -> System.out.println());
// Multiple elements
final List<String> stringsBefore = ImmutableList.of("", "foo", "bar");
System.out.println(stringsBefore);
final String stringsJson = gson.toJson(stringsBefore, listOfStringType);
System.out.println(stringsJson);
final List<String> stringsAfter = gson.fromJson(stringsJson, listOfStringType);
System.out.println(stringsAfter);
}
输出:
之前包装:
JSON:{}
包装后:null null - [!] not“”'“之前打包:foo
JSON:{“foo”:“foo”}
包装后:foo null - [!] not foo“”之前打包:吧
JSON:{“bar”:“bar”} 打包后:null bar - [!] not“”bar之前打包:foo bar
JSON:{“foo”:“foo”,“bar”:“bar”} 包装后:foo bar[,foo,bar]
[ “”, “富”, “杆”]
[,foo,bar]
但是,我不认为编写复杂(de)序列化策略是一个不错的选择,您可能对重新设计DTO和数据(de)序列化感兴趣。此外,""
是值,而null
则不是 - 我永远不会混合它们,我会修改为什么你的系统是这样设计的(它看起来真的像空/空值混合问题)。
答案 1 :(得分:2)
感谢@Lyubomyr的回答,但我找到了一个更适合我们用例的解决方案:
如果我们将所有空字符串和对象设置为null,则序列化后剩余的JSON只包含包含实际数据的节点:
/**
* convert object to json
*/
public String toJson(Object obj) {
// Convert emtpy string and objects to null so we don't serialze them
setEmtpyStringsAndObjectsToNull(obj);
return gson.toJson(obj);
}
/**
* Sets all empty strings and objects (all fields null) including sets to null.
*
* @param obj any object
*/
public void setEmtpyStringsAndObjectsToNull(Object obj) {
for (Field field : obj.getClass().getDeclaredFields()) {
field.setAccessible(true);
try {
Object fieldObj = field.get(obj);
if (fieldObj != null) {
Class fieldType = field.getType();
if (fieldType.isAssignableFrom(String.class)) {
if(fieldObj.equals("")) {
field.set(obj, null);
}
} else if (fieldType.isAssignableFrom(Set.class)) {
for (Object item : (Set) fieldObj) {
setEmtpyStringsAndObjectsToNull(item);
}
boolean setFielToNull = true;
for (Object item : (Set) field.get(obj)) {
if(item != null) {
setFielToNull = false;
break;
}
}
if(setFielToNull) {
setFieldToNull(obj, field);
}
} else if (!isPrimitiveOrWrapper(fieldType)) {
setEmtpyStringsAndObjectsToNull(fieldObj);
boolean setFielToNull = true;
for (Field f : fieldObj.getClass().getDeclaredFields()) {
f.setAccessible(true);
if(f.get(fieldObj) != null) {
setFielToNull = false;
break;
}
}
if(setFielToNull) {
setFieldToNull(obj, field);
}
}
}
} catch (IllegalAccessException e) {
System.err.println("Error while setting empty string or object to null: " + e.getMessage());
}
}
}
private void setFieldToNull(Object obj, Field field) throws IllegalAccessException {
if(!Modifier.isFinal(field.getModifiers())) {
field.set(obj, null);
}
}
private boolean isPrimitiveOrWrapper(Class fieldType) {
return fieldType.isPrimitive()
|| fieldType.isAssignableFrom(Integer.class)
|| fieldType.isAssignableFrom(Boolean.class)
|| fieldType.isAssignableFrom(Byte.class)
|| fieldType.isAssignableFrom(Character.class)
|| fieldType.isAssignableFrom(Float.class)
|| fieldType.isAssignableFrom(Long.class)
|| fieldType.isAssignableFrom(Double.class)
|| fieldType.isAssignableFrom(Short.class);
}
性能表现相当快。如果你有很多空字段,这可以在序列化和发送/写入数据库时节省时间(和空间)。