You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin序列化报错:无法解码含对象数组列表的JSON字符串

问题分析与解决方案

核心错误点

  1. 解码输入完全无效:接收代码里硬编码使用"kotlinx.serialization"作为JSON输入,这不是合法的JSON格式,直接触发解码失败。
  2. ActorModel序列化不完整:movieModelArrayList作为类成员变量,未被纳入@Serializable的序列化范围(data class默认仅序列化主构造函数内的属性),导致传递的JSON中丢失电影列表数据。
  3. 传递逻辑冗余:无需单独序列化电影列表,应让ActorModel的序列化结果直接包含其关联的电影列表。

步骤1:修复ActorModel的序列化逻辑

将movieModelArrayList移至主构造函数,确保序列化时包含该字段,同时简化序列化方法:

package com.sanjarbek.flixster2

import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import kotlinx.serialization.Serializable

@Serializable
data class ActorModel(
    val name: String,
    val popularity: String,
    val profile_path: String,
    // 将电影列表移到主构造函数,确保被序列化
    val movieModelArrayList: ArrayList<MovieModel> = arrayListOf()
) {
    // 简化序列化方法,直接序列化当前对象
    fun toJson(): String {
        return Json.encodeToString(this)
    }
}

步骤2:修正发送端代码

传递完整的ActorModel序列化字符串,无需单独处理电影列表:

holder.image.setOnClickListener {
    val intent = Intent(context, ActorInfoActivity::class.java)
    intent.putExtra("image", image_url)
    intent.putExtra("name", model.name)
    // 传递完整的ActorModel JSON数据
    intent.putExtra("actor_model", model.toJson())
    context.startActivity(intent)
}

步骤3:修正接收端解码逻辑

从Intent中取出正确的JSON字符串再执行解码:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_actor_info)

    // 从Intent中获取传递的JSON字符串
    val actorJson = intent.getStringExtra("actor_model") ?: ""
    if (actorJson.isNotEmpty()) {
        // 解码完整的ActorModel,包含关联的电影列表
        val actor = Json.decodeFromString<ActorModel>(actorJson)
        Log.d("TAG", "onCreate: 演员信息 $actor")
        Log.d("TAG", "onCreate: 关联电影数量 ${actor.movieModelArrayList.size}")
    } else {
        Log.e("TAG", "onCreate: 未获取到有效演员数据")
    }
}

额外优化建议

  • 替换ArrayList为Kotlin标准库的MutableList(序列化兼容性更好,且符合Kotlin编码习惯)。
  • 简化MovieModel的结构,去掉冗余的getter方法,直接使用Kotlin属性访问:
@Serializable
data class MovieModel (
    val original_title: String = "",
    val poster_path: String = "",
    val overview: String = ""
)
// 使用时直接访问:movie.original_title、movie.poster_path

内容的提问来源于stack exchange,提问作者Sanjarbek Kodirjonov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 12:01:20