Kotlin 使用 Gson 将 json 字符串转换为对象列表 [英] Kotlin convert json string to list of object using Gson

查看:195
本文介绍了Kotlin 使用 Gson 将 json 字符串转换为对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 Kotlin 编写从 JSON 字符串转换为对象列表的代码时遇到问题.

I have a problem with Kotlin to write code for conversion from JSON String to List of objects.

在Java中通常是这样的:

Normally in Java, it is like this:

  Gson gson = new Gson();
    Type type = new TypeToken<List<SomeOjbect>>() {}.getType();
    List<SomeOjbect> measurements = gson.fromJson(json, type);
    return measurements;

但是在 Kotlin 中,当我像这样尝试时:

However in Kotlin, when i try it like this:

   val gson = Gson()
    val type: Type = TypeToken<List<SomeOjbect>>{}.type
    val measurements : List<SomeOjbect> = gson.fromJson(text, type)
    return measurements 

IDE Android Studio 将 TypeToken 标记为错误:

The IDE Android Studio underlines as error the TypeToken saying:

无法访问 ' <init > ': 它是 public/package/在 'TypeToken'

Cannot access ' < init > ': it is public/package/ in 'TypeToken'

并且还强调 {} 说的错误:

and also underlines as error the {} saying:

类型不匹配.必需的:类型!成立:() → 单位

Type mismatch. Required: Type! Found: () → Unit

那么有没有办法让它适用于 Kotlin?

So is there a solution to make it work for Kotlin?

推荐答案

您可以尝试这样做:

val objectList = gson.fromJson(json, Array<SomeObject>::class.java).asList()

编辑 [2020 年 1 月 14 日]:您不应再使用 GSON.项目维护者之一 Jake Wharton 建议使用 Moshi、Jackson 或 kotlinx.serialization.

EDIT [14th January 2020]: You should NOT be using GSON anymore. Jake Wharton, one of the projects maintainers, suggests using Mos Jackson or kotlinx.serialization.

这篇关于Kotlin 使用 Gson 将 json 字符串转换为对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆