0

I have some difficulties to deserialise this JSON object from RIOT API:

{  
   "type":"champion",
   "version":"6.1.1",
   "data":{  
      "Thresh":{  
         "id":412,
         "key":"Thresh",
         "name":"Thresh",
         "title":"the Chain Warden"
      },
      "Aatrox":{  
         "id":266,
         "key":"Aatrox",
         "name":"Aatrox",
         "title":"the Darkin Blade"
      },...
    }
}

Inside the data object we have an other object with fields of all champions.

To not create all champions objects, I want de deserialise this to an list of Champion object, I expect something like that:

{  
   "type":"champion",
   "version":"6.1.1",
   "data":[
     {  
         "id":412,
         "key":"Thresh",
         "name":"Thresh",
         "title":"the Chain Warden"
      },
      {  
         "id":266,
         "key":"Aatrox",
         "name":"Aatrox",
         "title":"the Darkin Blade"
      },...
    ]
}

I think I have to create a custom Serializer that extends KSerialize but I didn't really know how to do it, can someone help me ?

On C# stackoverflow response is : Deserialize JSON from Riot API C#

MakiX
  • 326
  • 3
  • 8

1 Answers1

0

There is my solution: (If someone know witch descriptor to put there I'm interested)

object ChampionsSerializer : KSerializer<List<NetworkChampion>> {

    // TODO : Not the good descriptor, fix me
    override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("data", kind = PrimitiveKind.STRING)

    override fun deserialize(decoder: Decoder): List<NetworkChampion> {
        val jsonInput = decoder as? JsonDecoder ?: error("Can be deserialized only by JSON")
        val fieldsAsJson = jsonInput.decodeJsonElement().jsonObject
        val jsonParser = jsonInput.json

        return fieldsAsJson.map {
            jsonParser.decodeFromJsonElement(it.value)
        }
    }

    override fun serialize(encoder: Encoder, value: List<NetworkChampion>) {

    }
}
@Serializable
data class NetworkChampionsResponse(
    val type: String,
    val format: String,
    val version: String,
    @Serializable(ChampionsSerializer::class)
    val data: List<NetworkChampion>
)

Json link: https://ddragon.leagueoflegends.com/cdn/13.1.1/data/fr_FR/champion.json

MakiX
  • 326
  • 3
  • 8