Kotlinx.serialization缺失字段异常排查及解决
解决kotlinx.serialization.MissingFieldException:'words'字段缺失问题
报错详情
kotlinx.serialization.MissingFieldException: Field 'words' is required for type with serial name 'com.enestigli.dictionaryapp.data.locale.datamodel.WordsItem', but it was missing at kotlinx.serialization.internal.PluginExceptionsKt.throwMissingFieldException(PluginExceptions.kt:20) at com.enestigli.dictionaryapp.data.locale.datamodel.WordsItem.<init>(Word.kt:19) ...(省略部分栈跟踪) Suppressed: kotlinx.coroutines.DiagnosticCoroutineContextException: [StandaloneCoroutine{Cancelling}@c7efc65, Dispatchers.Main.immediate]
问题背景
在从Asset目录读取单词JSON文件、存入Room数据库再读取的流程中触发上述异常。
预期的JSON结构(对应数据模型)
最初设计的JSON为嵌套结构,外层数组包含带words字段的对象:
[ { "words": [ { "word": "the", "meaning": " “The sky is blue.” " }, { "word": "be", "meaning": "be – “Will you be my friend?”" }, ... ] } ]
配套的Kotlin序列化数据模型
@JvmInline @Serializable value class WordDataModel( val allData : List<WordsItem> ) @Serializable data class WordsItem( val words: List<CommonWords> ) { fun toEntity() = CommonWordEntity( words = words ) } @Serializable data class CommonWords( val word:String, val meaning:String )
实际使用的JSON结构
但Asset中实际使用的JSON是直接包含word和meaning对象的数组,没有外层的words嵌套:
[ { "word": "the", "meaning": " “The sky is blue.” " }, { "word": "be", "meaning": "be – “Will you be my friend?”" }, ... ]
解决方案
确认问题根源是误用了与数据模型不匹配的JSON文件,将Asset中的JSON替换为最初设计的嵌套结构(包含words字段的外层对象数组)后,序列化异常消失,流程正常运行。
内容的提问来源于stack exchange,提问作者NewPartizal
相关产品推荐
相关产品推荐

