Broken server response handling with Moshi

2019-07-20 04:39发布

问题:

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).