I use Moshi and I need to solve my problem with a buggy backend. Sometimes, when I request a list of objects, some of them don't contain mandatory fields. Of course, I can catch and process JsonDataException
, but I want to skip these objects. How can I do it with Moshi?
Update
I have a couple of models for my task
@JsonClass(generateAdapter = true)
data class User(
val name: String,
val age: Int?
)
@JsonClass(generateAdapter = true)
data class UserList(val list: List<User>)
and buggy JSON
{
"list": [
{
"name": "John",
"age": 20
},
{
"age": 18
},
{
"name": "Jane",
"age": 21
}
]
}
as you can see, the second object has no mandatory name
field and I want to skip it via Moshi adapter.
It seems I've found the answer
Thank you "guys from the other topics" =)
There's a gotcha in the solution that only catches and ignores after failure. If your element adapter stopped reading after an error, the reader might be in the middle of reading a nested object, for example, and then the next hasNext call will be called in the wrong place.
As Jesse mentioned, you can peek and skip the entire value.