0

I'm new to Kotlin & understanding the concepts as I move. Stuck in creating one type of Data class model where the response json structure as shown below

enter image description here

data class SPLPlayer(

    @field:Json(name ="id") val playerId: String?,
    val type: String?,
    @field:Json(name ="value") val currentValue: String?,
    @field:Json(name ="Confirm_XI") val isIn_XI:  Boolean = false,
    @field:Json(name ="Matches") val totalMatchs: String?,
    @field:Json(name ="Position") val position: String?,
    @field:Json(name ="Skill") val skill: String?,
    @field:Json(name ="skill_name") val skillName: String?,

    val teamId: String?,
    val name: String?, // other keys to refer Name_Full, short_name

    @field:Json(name ="Bowling") val bowler: SPLBowler? = null,
    @field:Json(name ="Batting") val batsmen: SPLBatsmen? = null


)

data class SPLTeamInfo (


     **How to parse the Team object which is dictionary**


)

Thanks & appreciate to every reader. Looking forward for the solution.

anandyn02
  • 259
  • 1
  • 3
  • 6

1 Answers1

-1

You should be able to use your own deserializer by adding annotation to a setter @set:JsonDeserialize() and passing your own deserializer implementation.

along the lines of:

import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import com.fasterxml.jackson.databind.JsonDeserializer
.. rest of imports

// for a given simplified json string
val json: String = """{"teams":{"1":{"name":"foo"},"2":{"name":"bar"}}}"""

class MyDeserializer : JsonDeserializer<List<Team>> {
    override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): List<Team>? {
        // iterate over each json element and return list of parsed teams
    }
}

data class JsonResp (
  @set:JsonDeserialize(using = MyDeserializer::class)
  var teams: List<Team>
)

data class Team (
  var id: String, // this is going to be a team key
  var name: String
)

Tried GitHub search with query @set:JsonDeserialize and it shows thousands of examples.

Ivar
  • 4,350
  • 2
  • 27
  • 29
  • `@set:JsonDeserialize` can't be used on the val fields of a data class: "'@set:' annotations could be applied only to mutable properties". – jebbench Feb 03 '21 at 17:24
  • Well I said `along the lines of` but for copy/pasters just changed to `var` – Ivar Feb 04 '21 at 09:59