Reputation: 1
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?
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
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
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