我正在尝试编写一个空安全列表适配器,该适配器将可空列表序列化为不可空对象。我知道您可以执行以下操作:
object {
@FromJson
fun fromJson(@Nullable list: List<MyObject>?): List<MyObject> {
return list ?: emptyList()
}
@ToJson
fun toJson(@Nullable list: List<MyObject>?) = list ?: emptyList()
这对List<MyObject>
有效,但如果我使用List<Any>
或List<T>
,则无效。有什么办法可以使它适用于所有列表?
答案 0 :(得分:0)
@FromJson
/ @ToJson
适配器尚不支持List之类的泛型。它们直接匹配类型。您将需要完整写出的JsonAdapter.Factory。请记住将NullToEmptyListJsonAdapter.FACTORY
添加到您的Moshi.Builder
中。
final class NullToEmptyListJsonAdapter extends JsonAdapter<List<?>> {
static final Factory FACTORY = new Factory() {
@Nullable @Override
public JsonAdapter<?> create(Type type, Set<? extends Annotation> annotations, Moshi moshi) {
if (!annotations.isEmpty()) {
return null;
}
if (Types.getRawType(type) != List.class) {
return null;
}
JsonAdapter<List<?>> objectJsonAdapter = moshi.nextAdapter(this, type, annotations);
return new NullToEmptyListJsonAdapter(objectJsonAdapter);
}
};
final JsonAdapter<List<?>> delegate;
NullToEmptyListJsonAdapter(JsonAdapter<List<?>> delegate) {
this.delegate = delegate;
}
@Override public List<?> fromJson(JsonReader reader) throws IOException {
if (reader.peek() == JsonReader.Token.NULL) {
reader.skipValue();
return emptyList();
}
return delegate.fromJson(reader);
}
@Override public void toJson(JsonWriter writer, @Nullable List<?> value) throws IOException {
if (value == null) {
throw new IllegalStateException("Wrap JsonAdapter with .nullSafe().");
}
delegate.toJson(writer, value);
}
}