如何使用Moshi将JSON中字符串格式的数组字段反序列化为对象列表?
使用Moshi将嵌套JSON字符串反序列化为列表
问题背景
给定的JSON中actions字段是被引号包裹的JSON数组字符串,直接用默认Moshi解析无法转换为Kotlin的List<Action>类型,需要通过自定义适配器处理这种特殊格式。
步骤实现
1. 补全Kotlin数据类
先修正原代码中缺失的类名:
data class Item( val title: String, val actions: List<Action> ) data class Action( val label: String )
2. 编写自定义Moshi适配器
创建适配器类,负责完成JSON字符串到List<Action>的转换:
import com.squareup.moshi.FromJson import com.squareup.moshi.Moshi import com.squareup.moshi.ToJson import com.squareup.moshi.Types class ActionListAdapter(private val moshi: Moshi) { @FromJson fun fromJson(actionsJson: String): List<Action> { val listType = Types.newParameterizedType(List::class.java, Action::class.java) val adapter = moshi.adapter<List<Action>>(listType) // 解析失败时返回空列表,可根据业务需求改为抛出异常 return adapter.fromJson(actionsJson) ?: emptyList() } // 若需要将List<Action>序列化为JSON字符串,保留此方法;无需序列化则删除 @ToJson fun toJson(actions: List<Action>): String { val listType = Types.newParameterizedType(List::class.java, Action::class.java) val adapter = moshi.adapter<List<Action>>(listType) return adapter.toJson(actions) } }
3. 配置Moshi并执行反序列化
初始化Moshi时注册自定义适配器,再完成JSON解析:
// 初始化Moshi实例,注册适配器和Kotlin支持工厂 val moshi = Moshi.Builder() .add(ActionListAdapter(Moshi.Builder().build())) .add(KotlinJsonAdapterFactory()) .build() // 待解析的原始JSON字符串 val rawJson = """{ "title": "foo", "actions": "[ { \"label\": \"Hello\" } ]" }""" // 执行反序列化 val itemAdapter = moshi.adapter(Item::class.java) val item = itemAdapter.fromJson(rawJson)
注意事项
- 确保嵌套的
actions字符串是合法的JSON格式,转义符和结构不能有误,否则解析会抛出异常 - 可根据业务需求调整适配器中的错误处理逻辑(比如解析失败时抛出异常而非返回空列表)
内容的提问来源于stack exchange,提问作者der_Fidelis
相关产品推荐
相关产品推荐

