Kotlin Serialization: Json Parse MissingFieldException (Field 'x' is required, but it was missing)

Optional field

The json string sometimes doesn't contain mediaItemsCount (optional field), thus it is necessary to provide a default value for mediaItemsCount to avoid the following error.

kotlinx.serialization.MissingFieldException: Field 'mediaItemsCount' is required, but it was missing
@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.