Unresolved reference: TypeToken

I`m using JSON for the first time and I have a problem. When I try to use and import TypeToken, I get the error "Unresolved reference: TypeToken".

My code

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

import com.google.gson.Gson
import java.lang.reflect.Type
import com.google.gson.reflect.TypeToken

class QuizActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_quiz)

        val gson = Gson()

        val json = "quiz.json"
        val myType: Type = object : TypeToken<List<QuizType>>(){}.type()
        val quiz: List<QuizType> = gson.fromJson(json, myType)

    }
}

What is wrong?


Edited

I will use this

val myType = typeOf<List<QuizType>>().javaType

instead

val myType: Type = object : TypeToken<List<QuizType>>(){}.type()

And it works! (Or I will try Moshi)

Upvotes: 0

Views: 2387

Answers (2)

Devrim Catak
Devrim Catak

Reputation: 66

I added these below lines in progurard. It works for me.

-keep,allowobfuscation,allowshrinking class com.google.gson.reflect.TypeToken
-keep,allowobfuscation,allowshrinking class * extends com.google.gson.reflect.TypeToken

Upvotes: 0

Mayur Gajra
Mayur Gajra

Reputation: 9073

There's is issue in declaration of TypeToken. You're missing object : in front. Because it's supposed to be Anonymous Inner Class.

It should be like this:

val gson = Gson()
val json = "quiz.json"
val myType: Type = object : TypeToken<List<QuizType>>() {}.type
val quiz: List<QuizType> = gson.fromJson(json, myType)   

  

Upvotes: 1

Related Questions