【问题标题】:Why Kotlin is not processing my list of Arrays为什么 Kotlin 不处理我的数组列表
【发布时间】:2019-03-21 17:01:45
【问题描述】:

我从 Kotlin 代码中的 json api 获取数据。我可以正确解析字符串值的数据,但解析数组列表会导致问题。

我的回复数据如下

{
    "limit": "10",
    "schedule": {
        "0": ["0", "3.00", "7.59", "9.00", "12.59", "14.00", "22.59"],
        "1": ["1", "3.00", "7.59", "9.00", "12.59", "14.00", "22.59"],
        "2": ["2", "3.00", "7.59", "9.00", "12.59", "14.00", "22.59"],
        "3": ["3", "3.00", "7.59", "9.00", "12.59", "14.00", "22.59"],
        "4": ["4", "3.00", "7.59", "9.00", "12.59", "14.00", "22.59"],
        "5": ["5", "3.00", "7.59", "9.00", "12.59", "14.00", "22.59"],
        "6": ["6", "3.00", "7.59", "9.00", "12.59", "14.00", "22.59"]
    },
    "target_temp": "32.18"
}

现在要检索值,例如 target_temp 我正在成功使用以下代码

val gson = GsonBuilder().create() 
 val target = gson.fromJson(body, data::class.java)        println(target.target_temp)

我的课程代码很简单

class data(val target_temp: String)

现在,当我想访问计划时,我得到了错误。

java.lang.IllegalStateException: 应为 BEGIN_ARRAY,但在第 1 行第 50 列路径 $.schedule 处为 BEGIN_OBJECT

我的检索时间表的代码如下。

val gson = GsonBuilder().create()
val schedule = gson.fromJson(body, schedule::class.java)
println(schedule.schedule.get(1))

课程安排是

class schedule(val schedule: ArrayList<String>)

【问题讨论】:

  • 虽然你应该阅读kotlinlang.org/docs/reference/coding-conventions.html - 不能解决问题,但它仍然很重要
  • 您的数据类不代表您尝试处理的 Json 数据。例如:数据没有属性limit
  • 我编辑了你的数据集。您可以看到您的映射类没有映射实际的 json 结构。
  • @AlexanderEgger 我的数据类忽略了限制,因为我不需要那些信息
  • @shkschneider 但我正在检索 target_temp 值

标签: android kotlin


【解决方案1】:

在您的响应模型中设置schedule 变量数据类型Map&lt;String, List&lt;String&gt;&gt; 而不是ScheduleobjectList&lt;String&gt;

您的响应模型如下所示

data class ResponseModel(
   val schedule: Map<String, List<String>>,
   val target_temp: String
)

【讨论】:

    【解决方案2】:

    计划不是ArrayList&lt;String 类型,而是Map&lt;ArrayList&lt;String&gt;&gt; 类型。

    将您对时间表的定义更改为:

    class schedule(val schedule: Map<String, ArrayList<String>>)
    

    完整示例:

    val gson = GsonBuilder().create()
    val schedule = gson.fromJson(body, schedule::class.java)
    println(schedule.schedule.get("0"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-09
      • 2021-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-14
      • 1970-01-01
      相关资源
      最近更新 更多