使用 Moshi 处理损坏的服务器响应

Broken server response handling with Moshi

来自服务器的预期 json 响应应为:

{
  "teacher": {
    "123": {
      "_id": "389",
      "name": "test_fast_teacher1"
    }
  }
}

服务器返回 json :

{
  "teacher": [

  ]
}

无论如何要处理这个损坏的 json 响应? 在我从 Gson 切换之前,教师对象仍将被反序列化,只是它将为空。通过使用 Moshi,会抛出错误,我无法继续正确序列化的另一个 json。

作者的回复请参考the link

这样的怎么样?

Moshi moshi = new Moshi.Builder()
    .add(DefaultOnDataMismatchAdapter.newFactory(Teacher.class, null))
    .build();

JsonAdapter<Teacher> adapter = moshi.adapter(Teacher.class);

Teacher teacher = adapter.fromJson(json);
// teacher == null

其中 DefaultOnDataMismatchAdapterJesse's code you can copy into your code base.

当 Teacher 类型以会产生 JsonDataException 的意外格式返回时,它将默认返回到您的设置值(在本例中为 null)。