Generic Data class in Kotlin - kotlin

Create a generic data class which has one variable data Type
data class <T> GenericResponse(
val success: Boolean,
val message: String,
val data: T
)
To use it: GenericResponse<SomeOtherDataClass>
How to do this in kotlin?

Just put the <T> after the class name:
data class GenericResponse<T>(
val success: Boolean,
val message: String,
val data: T
)

Related

Can you use a JsonPath with a JsonProperty Annotation

I have a Kotlin data class that I want to map to some Json - common as rain, by itself. What I'd like to do is represent each field as a JsonPath expression in the #JsonAttribute field because the result I get is an array with 1 single map in it - something like this:
data class Bug(
#JsonProperty("\$.items[0].rptno")
val id: Long,
val status: Int,
#JsonProperty("\$.items[0].updated_date")
val reportedDate: Instant, // fields.created
#JsonProperty("updated_date")
val updatedDate: Instant,
val pillar: String, // from pi file as pillar
#JsonProperty("\$.items[0].product_id")
val productId: Int,
#JsonProperty("\$.items[0].assignee")
val assignee: String,
val serviceRequests: List<Long> = listOf(),
#JsonProperty("\$.items[0].subject")
val title: String,
#JsonProperty("\$.items[0].bug_type")
val type: String,
)

Kotlin Data class setter using class fields

I have a redis entity using a kotlin data class and its Id should be a combination of few other fields from the same class.
Can this be achieved by defining setter for Id field instead of computing it outside of data class?
#RedisHash("Game")
data class Game(
#Id
val generatedId: String = "Default_ID",
val name: String,
val location: String,
val homeTeam: String,
val awayTeam: String
)
// want something like this
var generatedId : String = "DEFAULT_ID"
get() = "${name}${location}"
// or even better
var generated_Id : String = "${name}${location}"
Did you try to do something like this?
#RedisHash("Game")
data class Game(
val name: String,
val location: String,
val homeTeam: String,
val awayTeam: String,
#Id
val generatedId: String = "${name}${location}"
)

Create customise Data class model using Kotlin Koin

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
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.
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.

Transform data class to map kotlin

My problem is that I need to transform a data class in kotlin to a map, because I need to work with this structure as a requirement, because this response will be used for a groovy classes and there is a post-process where there are validations iterations etc, with this map. My data class is the next (Podcast):
data class PodCast(val id: String, val type: String, val items: List<Item>, val header: Header, val cellType:String? = "")
data class Item(val type: String, val parentId: String, val parentType: String, val id: String, val action: Action, val isNew: Boolean)
data class Header(val color: String, val label: String)
data class Action(val type: String, val url: String)
I made the transformation manually, but I need a more sophisticated way to achieve this task.
Thanks.
You can also do this with Gson, by serializing the data class to json, and then deserializing the json to a map. Conversion in both directions shown here:
val gson = Gson()
//convert a data class to a map
fun <T> T.serializeToMap(): Map<String, Any> {
return convert()
}
//convert a map to a data class
inline fun <reified T> Map<String, Any>.toDataClass(): T {
return convert()
}
//convert an object of type I to type O
inline fun <I, reified O> I.convert(): O {
val json = gson.toJson(this)
return gson.fromJson(json, object : TypeToken<O>() {}.type)
}
See similar question here
I have done this very simple. I got the properties of the object, just using the .properties groovy method, which gave me the object as a map.

Generic jsonObjectparsing using gson

Hi there im trying to make a generic client and trying to parse the json to a object.
gson?.fromJson(khttpResponse.jsonObject.toString(),
UserInfo::class.java)
works.
val listType = object : TypeToken<T>() {}.type
gson?.fromJson(khttpResponse.jsonObject.toString(), listType)
Doesnt't work. So my question is there a workaround to to parse json in gson or do you guys use some other libary?
UserInfo:
open class UserInfo (
val profileId: String,
val code: String,
val message: String,
val path: String,
val profile: Profile,
val errorDetail: Any
)
data class Profile(
val firstname: String,
val lastname: String
)