Kotlin使用Gson将json字符串转换为ojbect列表 [英] Kotlin convert json string to list of ojbect using Gson
本文介绍了Kotlin使用Gson将json字符串转换为ojbect列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
$ b
Gson gson = new Gson();
Type type = new TypeToken< List< SomeOjbect>>(){} .getType();
列表< SomeOjbect>度量= gson.fromJson(json,type);
返回测量值;
然而在Kotlin中,当我试试这样的时候:
val gson = Gson()
val type:Type = TypeToken< List< SomeOjbect>> {}。类型
val测量:List< SomeOjbect> = gson.fromJson(text,type)
返回度量值
IDE Android Studio强调为错误的TypeToken说:
无法访问'< init>':它是公共/ 包 /在'TypeToken'中
并且强调为错误{}说:
类型不匹配。
必需:
类型!
找到:
()→单位
那么是否有解决方案可以使它适用于Kotlin?
解决方案
您可以尝试这样做:
val objectList = gson.fromJson(json,Array< SomeObject> :: class.java).asList()
这应该做的工作
I have a problem with Kotlin to write code for conversion from json String to List of objects.
Normaly 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;
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
The IDE Android Studio underlines as error the TypeToken saying:
Cannot access ' < init > ': it is public/package/ in 'TypeToken'
and also underlines as error the {} saying:
Type mismatch. Required: Type! Found: () → Unit
So is there a solution to make it work for Kotlin?
解决方案
You could try doing this instead:
val objectList = gson.fromJson(json, Array<SomeObject>::class.java).asList()
This should do the work
这篇关于Kotlin使用Gson将json字符串转换为ojbect列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文