0

I try to parse this json {"value": [1, "a", "b"]} to triple object. Gson doesn't even call my deserialize.

class TripleDeserializer: JsonDeserializer<Triple<Int, String, String>> {
    override fun deserialize(
        json: JsonElement?,
        typeOfT: Type?,
        context: JsonDeserializationContext?
    ): Triple<Int, String, String> {
        val f = json!!.asJsonArray.get(0).asInt
        val s = json.asJsonArray.get(1).asString
        val t = json.asJsonArray.get(2).asString
        return Triple(f, s, t)
    }
}

class SomeClass(val value: Triple<Int, String, String>)

fun another() {
    val input = "{\"value\": [1, \"a\", \"b\"] }"
    val type = object : TypeToken<Triple<Int, String, String>>() {}.type
    val gson = GsonBuilder()
        .registerTypeAdapter(type, TripleDeserializer())
        .create()
    val out = gson.fromJson(input , SomeClass::class.java)
}
Sergey
  • 113
  • 1
  • 5
  • Why do you expect gson will call your deserializer? You should instruct it to deserialize it to a Triple `gson.fromJson(input , type)` provide your type-token's type – Animesh Sahu Apr 28 '20 at 04:22
  • Does this answer your question? [Deserializing Generic Types with GSON](https://stackoverflow.com/questions/18397342/deserializing-generic-types-with-gson) – Animesh Sahu Apr 28 '20 at 04:26
  • Not really, when I register deserializer for types like String, Int etc gson always call it. But in my case he don't see that variable "value" and registered adapter have the same type. gson.fromJson("[1,\"10:00\",\"19:00\"]", type) works fine – Sergey Apr 28 '20 at 13:29

0 Answers0