36

I know a lot of similar questions here in StackOverflow, but nothing solved mine.

I have a generic data class:

  data class ServiceCall<out T>(val result: T?, val exception: String?, val pagination: String?, val stringResult: String?)

I am trying to use like this:

Gson().fromJson(json, ServiceCall<SurveyListModel>::class.java).result

IDE shows error: only classes are allowed on the left hand side of a class literal

How to solve this? Thanks in advance.

Bhuvanesh BS
  • 13,474
  • 12
  • 40
  • 66

3 Answers3

47

You can't use generics with class, as easily observable here:

List<Int>::class.java

It gives you the same error. To use the generic typ in GSON deserialization, do what is suggested here:

https://stackoverflow.com/a/5554296/8073652

EDIT:

In Kotlin it looks like this:

val type: Type = object : TypeToken<ServiceCall<SurveyListModel>>() {}.type 
Gson().fromJson<ServiceCall<SurveyListModel>>(json, type).result

Here's a small proof of concept, I've written:

 class Token : TypeToken<List<Int>>()
 val x: List<Int> = Gson().fromJson(Gson().toJson(arrayOf(1)), Token().type)
 println(x)
s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
3

If someone looking for the answer in Kotlin and Jackson.

val response = ObjectMapper().convertValue(dataObject, object: TypeReference<Map<String, Any>>(){})
Mohan
  • 457
  • 6
  • 15
2

If you want to pass a list of the generic objects pass it like this

listOf<MyModel>()::class

the function will be like this

fun myFunction ( inputList: KClass<T>){}
Hesham Yemen
  • 437
  • 5
  • 6