Android中如何用Moshi Kotlin将动态分组JSON转为数据类对象?
解决Moshi动态分组JSON反序列化问题
核心思路
放弃固定字段的数据类,改用自定义反序列化器将所有group开头的动态字段映射到Map中,同时保留固定的groups字段,彻底避免新增分组时重编译应用。
步骤实现
1. 定义基础数据类
先明确分组内元素的结构:
data class WordDesc( val word: String, val description: String )
2. 定义目标数据类
包含固定的groups字段,以及存储动态分组的groupMap:
data class Dictionary( val groups: List<String>, val groupMap: Map<String, List<WordDesc>> )
3. 编写自定义Moshi反序列化器
实现FromJson方法手动解析JSON:遍历所有字段,groups字段直接解析,group开头的字段存入Map,忽略其他未知字段:
class DictionaryAdapter { @FromJson fun fromJson(reader: JsonReader): Dictionary { var groups: List<String>? = null val groupMap = mutableMapOf<String, List<WordDesc>>() val moshi = Moshi.Builder().build() val stringListAdapter = moshi.adapter<List<String>>() val wordDescListAdapter = moshi.adapter<List<WordDesc>>() reader.beginObject() while (reader.hasNext()) { when (val fieldName = reader.nextName()) { "groups" -> groups = stringListAdapter.fromJson(reader) else -> { if (fieldName.startsWith("group")) { wordDescListAdapter.fromJson(reader)?.let { groupMap[fieldName] = it } } else { reader.skipValue() } } } } reader.endObject() return Dictionary(groups ?: emptyList(), groupMap) } }
4. 配置Moshi并解析JSON
创建Moshi实例时注册自定义适配器,再执行反序列化:
val moshi = Moshi.Builder() .add(DictionaryAdapter()) .add(KotlinJsonAdapterFactory()) .build() val dictionary = moshi.adapter<Dictionary>().fromJson(fileInString)
错误原因说明
你之前遇到的Required value 'dict' missing错误,是因为数据类中定义了JSON不存在的dict字段,Moshi默认将未标记为可空的字段视为必填项,因此抛出异常。上述方案完全规避了不存在的字段,直接将动态分组映射到Map中。
内容的提问来源于stack exchange,提问作者Tropic
相关产品推荐
相关产品推荐

