Skip to content

Moshi failOnUnknown() isn't working as expected #1

@ColtonIdle

Description

@ColtonIdle

I'm new to using Moshi and Kotlin. I was excited to see that you have the ability to fail when you hit unexpected json.

The thing is, it didn't seem to work for me in my real project, so I created this sandbox project.

I want to fail in two scenarios (especially during development). Arguably, I may want to disable this or be more lenient in production.

The two scenarios I want to fail are as follows:

  1. If I'm expecting something to be there in my model (that came from the network), but it isn't there.

  2. When the key is in my JSON but absent in your model.

In this project I'm using a freely available API call: https://jsonplaceholder.typicode.com/todos/1

It returns

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

If my model is setup as

data class Todos(
        val userId: Int = 0,
        val id: Int = 0,
        val title: String = "",
        val completed: Boolean = false
)

then everything works fine. If I remove the 'd' from userId then I fail with an error of "Cannot skip unexpected name..." This satisfies scenario 1 that I want to fail in. The message to me doesn't make sense though. Something like "Cannot skip expected name" makes more sense for this scenario.

To satisfy scenario 2, I try inserted a value that I assume to be necessary.

data class Todos(
        val userId: Int = 0,
        val id: Int = 0,
        val title: String = "",
        val completed: Boolean = false,
        val assumeINeedThis: Boolean = false
)

This doesn't cause any issues. Additionally if I remove the default value, then this still doesn't cause any issues.

data class Todos(
        val userId: Int = 0,
        val id: Int = 0,
        val title: String = "",
        val completed: Boolean = false,
        val assumeINeedThis: Boolean
)

Does anyone have any thoughts on how to trigger scenario 2?
Follow up: Is there any clever way to always have default values and turn off failOnUnknown for production build variants?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions