4

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.

wenyang9319
  • 180
  • 2
  • 13

1 Answers1

3

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

Eric Cochran
  • 8,414
  • 5
  • 50
  • 91
  • If any problem in any inner class occurs, it will return an empty object. How to overcome it and return a normal object? – CoolMind Feb 15 '19 at 14:10
  • @CoolMind Can you open a new question and show what you mean with example code or a test case? – Eric Cochran Feb 15 '19 at 19:12
  • See my solution with `Gson` in https://stackoverflow.com/questions/54668805/delete-empty-arrays-in-gson/. I tried `Moshi`, but in a complex `JSON` DefaultOnDataMismatchAdapter catches an error, then returns `null`. – CoolMind Feb 19 '19 at 10:39
  • @EricCochran how could this be done for any class? I want to avoid adding every class that could be a mismatch. If I add the top-level, it skips the whole top-level object. In my case, nested Arrays can come back "[]" when they are null. Maybe there is a better solution than detecting a mismatch? – Codeversed Mar 11 '19 at 19:04
  • 1
    @Codeversed use JsonReader.peek() and delegate from there. https://github.com/square/moshi/blob/master/examples/src/main/java/com/squareup/moshi/recipes/MultipleFormats.java may be helpful. – Eric Cochran Mar 11 '19 at 23:28
  • @EricCochran thanks, this was what I was planning on doing but wanted to confirm there was not an easier path forward. It's odd that it's not built in to handle empty arrays or objects since this is standard in the JSON spec: https://jsonapi.org/format/#document-resource-object-linkage I am sure there is a reason though :) – Codeversed Mar 12 '19 at 12:29
  • @EricCochran Disregard that last comment... Moshi does work to spec, it was our API sending the wrong empty cases back #facepalm In short, I learned a lot about parsing and Moshi works as expected lol – Codeversed Mar 12 '19 at 17:03