使用Moshi处理服务器响应失败 [英] Broken server response handling with Moshi
问题描述
服务器的预期json响应应为:
The expected json response from server should be :
{
"teacher": {
"123": {
"_id": "389",
"name": "test_fast_teacher1"
}
}
}
服务器返回json:
{
"teacher": [
]
}
无论如何处理这个损坏的json响应? 在我从Gson切换之前,该教师对象仍将反序列化,只是它将为null.通过使用Moshi,将抛出错误,并且我无法继续正确序列化的其他json.
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 Mos 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.
推荐答案
这样的事情怎么样?
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
其中DefaultOnDataMismatchAdapter
是您可以将Jesse的代码复制到代码库中.
当Teacher类型以意外的格式返回时,会产生JsonDataException,它将默认返回到您的设置值(在这种情况下为null).
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).
这篇关于使用Moshi处理服务器响应失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!