bean json转kotlin,Kotlin使用Gson将json字符串转换为ojbect列表

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>() {}.getType();

List measurements = gson.fromJson(json, type);

return measurements;

However in Kotlin, when i try it like this:

val gson = Gson()

val type: Type = TypeToken>{}.type

val measurements : List = 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::class.java).asList()

This should do the work

你可能感兴趣的:(bean,json转kotlin)