Kotlin Serialization: Json Parse JsonDecodingException (Encountered an unknown key x)

Extra json fields

In cases where the json string contain additional fields/keys which shall not be deserialize into a object, we need to use a non strict json object to avoid the following error (coverPhotoMediaItemId is not decoded into object).

kotlinx.serialization.json.JsonDecodingException: Invalid JSON at 158: Encountered an unknown key coverPhotoMediaItemId
@Serializableclass GooglePhotosAlbumListResult(val albums: List<Album>) {    @Serializable    class Album(        val id: String,        val title: String?,        val coverPhotoBaseUrl: String?,        val mediaItemsCount: Int? = null)}
// Use non strict mode if json string have extra fields which won't be serialize into object// val json = Json.nonstrictval json = Json(JsonConfiguration.Stable.copy(strictMode = false))val jsonString = """{  "albums": [    {      "mediaItemsCount": "7",      "coverPhotoMediaItemId": "AOYE...",      "coverPhotoBaseUrl": "https://lh3.googleusercontent.com/...",      "id": "AOYE...",      "productUrl": "https://photos.google.com/...",      "title": "Taiwan"    },    {      "coverPhotoBaseUrl": "https://lh3.googleusercontent.com/...",      "id": "AOYE...",      "productUrl": "https://photos.google.com/...",      "title": "Empty"    }  ]}"""val item = json.parse(GooglePhotosAlbumListResult.serializer(), jsonString)

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.