【问题标题】:Moshi deserialise null to empty listMoshi 将 null 反序列化为空列表
【发布时间】:2019-03-16 02:54:33
【问题描述】:

我正在尝试编写一个空安全列表适配器,它将一个可为空的列表序列化为一个不可为空的对象。我知道你可以这样做:

object {
   @FromJson
   fun fromJson(@Nullable list: List<MyObject>?): List<MyObject> {
                return list ?: emptyList()
   }

    @ToJson
    fun toJson(@Nullable list: List<MyObject>?) = list ?: emptyList()

这适用于List&lt;MyObject&gt;,但如果我使用List&lt;Any&gt;List&lt;T&gt;,它就不起作用。有没有办法让它适用于所有列表?

【问题讨论】:

    标签: json kotlin null moshi


    【解决方案1】:

    @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);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-04-03
      • 2012-03-25
      • 2016-09-16
      • 1970-01-01
      • 1970-01-01
      • 2016-11-09
      • 2019-12-19
      • 1970-01-01
      • 2021-12-22
      相关资源
      最近更新 更多