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)