Broken server response handling with Moshi

不问归期 提交于 2019-12-11 02:15:49

问题


The expected json response from server should be :

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

Server returned json with this :

{
  "teacher": [

  ]
}

Anyway to handle this broken json response? Before I switching from Gson, the teacher object will still be deserialised, just that it will be null. By using Moshi, the error would be threw and I can't proceed with the other json which is serialised correctly.

Please refer to the link for the reply from author.


回答1:


How about something like this?

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

where DefaultOnDataMismatchAdapter is Jesse's code you can copy into your code base.

When the Teacher type comes back in an unexpected format that would produce a JsonDataException, it will default back to your set value (in this case, null).



来源:https://stackoverflow.com/questions/47101598/broken-server-response-handling-with-moshi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!