hello everyone in ktor when some expected fields i...
# ktor
r
hello everyone in ktor when some expected fields isn't received in the response I got an io.ktor.serialization.JsonConvertException: Illegal input: Fields [name] are required for type with serial name 'UserDTO', but they were missing at path: $.User.name
a
Can you describe the problem?
r
I expect the not received fields to be ignored if not received
m
This error occurs because your DTO class expects certain fields that aren't present in the JSON response. You can go about it with one of these: • Make Fields Nullable
Copy code
@Serializable
data class DTO(val name: String? = null)
• Add Default Values
Copy code
@Serializable
data class DTO(val name: String = "default-name")
isLenient
to true In your Json configuration from
kotlinx.serlization
inside
ktor
you can set
isLenient
to true
👌 1
r
but this is different from retrofit in retrofit it will ignore it by default
m
Retrofit is using Gson for serlization while ktor is using kotlinx.serlization Different libs, different behaviour There is also
ignoreUnknownKeys
to ignore any keys that are extra or you don't want to add to your model
Copy code
install(ContentNegotiation) {
        json(Json {
            isLenient = true            
            ignoreUnknownKeys = true // Ignore unknown keys in JSON (optional)
        })
    }
example
Copy code
{
  "username": "moussa147",
  "pass": "123456",
  "hello": "world"
}
Copy code
@Serializable
data class Model(val username: String, val pass: String)
When you use
ignoreUnknownKeys
it will ignore the
hello
in the
JSON
r
got you thank you @Moussa 🙏