0

I need get breadType property from Sandwich class. I have 2 clases both serializable:

@Serializable
class MyFood {
    var name: String? = null
    var price: Int? = null
    var sand: Sandwich? = null
}

@Serializable
class Sandwich{
    var breadType: String? = null
}

And this JSON:

"MyFood": {
    "name": "Sandwich double",
    "price": 100.00,
    "breadType": 100.00
 }

I get JsonUnknownKeyException exception:

"Strict JSON encountered unknown key: breadType\nYou can disable strict mode to skip unknown keys"

What I do wrong please!?

Andy
  • 751
  • 1
  • 12
  • 25

1 Answers1

0

If you are using Retrofit:

Use JsonConfiguration(strictMode = false) on retrofit converter factory.

// your retrofit builder
.addConverterFactory(
    Json(
        JsonConfiguration(strictMode = false)
    ).asConverterFactory(MediaType.get("application/json"))
)

In other words,You should use Json.nonstrict.parse() instead of Json.parse()

Or we can pass in constructor:

serializer = KotlinxSerializer(Json.nonstrict)

Edited:

As per your json your class should be like this:

Serializable
class MyFood {
    var name: String? = null
    var price: Int? = null
    var breadType: double? = null
}

This will work but if you want to use Sandwich class then your json should be like this:

"MyFood": { 
    "name": "Sandwich double",
    "price": 100.00, 
    "sand": {
        "breadType":100.00
    }
}
hippietrail
  • 15,848
  • 18
  • 99
  • 158
Muazzam A.
  • 647
  • 5
  • 17