Can you use a JsonPath with a JsonProperty Annotation - jackson

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,
)

Related

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.

kotlin-room figure out how to save this field

I upload information to the Book class.
tableName = "Books_name" data class Books( // #Embedded // val additional_imgs: MutableList<String>, val adult: Int, val author: String, val bookmark: Int, val chapters: MutableList<Chapter>? = null, val chapters_total: Int, // #Embedded // val comments: MutableList<Comment>, autoGenerate = true val id: Int? = null, val img: String, val lang: String, val last_activity: Int, val n_chapters: Int, val publisher: String, val rating: String, val s_title: String, val status: String, val t_title: String, // val team: Int, val writer: String, val year: String )
Book has a class Chapter
//#Entity(tableName = "Books_name")
data class Chapter(
val can_read: Boolean,
// autoGenerate = true
val id_glavs_list: Int,
val new: Boolean,
val status: String,
val title: String
)
But after adding this class, an error appears. I was looking for information, but everywhere they say that this is corrected by cleaning the project. But it does not help. EROR:
Entities and Pojos must have a usable public constructor. You can have
an empty constructor or a constructor whose parameters match the
fields (by name and type). - java.util.List

kotlin default value in data class is aways zero [duplicate]

This question already has answers here:
Gson Deserialization with Kotlin, Initializer block not called
(2 answers)
Closed 4 years ago.
I've a simple data class of User
data class User(#PrimaryKey(autoGenerate = true) val id: Long, val _id: String, val name: String, val about: String,
val phoneNumber: String, val token: String,
val lastLogin: String, val avatarUrl: String, #Embedded val location: Location,
val emailId: String, val gender: Boolean, val timestamp: Long = System.currentTimeMillis())
As you can see the last parameter is val timestamp: Long = System.currentTimeMillis()
the response comes from network using retrofit and parsed using GSON
timestamp does not comes in a response json it's just extra field I need to do some logic. The problem is that value is always 0. It should be the current time stamp
This will do the trick,
data class User(#PrimaryKey(autoGenerate = true) val id: Long, val _id: String, val name: String, val about: String,
val phoneNumber: String, val token: String,
val lastLogin: String, val avatarUrl: String, #Embedded val location: Location,
val emailId: String, val gender: Boolean) {
var timestamp: Long = System.currentTimeMillis()
get() = if(field > 0) field else {
field = System.currentTimeMillis()
field
}
}

Using Moshi with multiple input fields

I have some JSON that looks like this:
{
"name" : "Credit Card",
"code" : "AUD",
"value" : 1000
}
and am using Moshi to unmarshall this into a data structure like:
data class Account(
#Json(name = "name")
val name: String,
#Json(name = "currency")
val currency: String,
#Json(name = "value")
val value: Int
)
Everything works well. However, I really would like to extract the currency and value parameters into a separate Money object. So my model looks more like:
data class Money(
#Json(name = "currency")
val currency: String,
#Json(name = "value")
val value: Int
)
data class Account(
#Json(name = "name")
val name: String,
#Json(name = "???")
val money: Money
)
The challenge I'm struggling with is how to annotate things so that the Money object can be given two different fields (currency and value) that come from the same level as the parent account.
Do I need to create an intermediate "unmarshalling" object called, say, MoshiAccount and then use a custom adapter to convert that to my real Account object?
I saw How to deseralize an int array into a custom class with Moshi? which looks close (except that in that case, the adapted object (VideoSize) only needs a single field as input... in my case, I need both currency and value)
Any thoughts or suggestions would be much appreciated. Thanks
Moshi's adapters can morph your JSON structure for you.
object ADAPTER {
private class FlatAccount(
val name: String,
val currency: String,
val value: Int
)
#FromJson private fun fromJson(json: FlatAccount): Account {
return Account(json.name, Money(json.currency, json.value))
}
#ToJson private fun toJson(account: Account): FlatAccount {
return FlatAccount(account.name, account.money.currency, account.money.value)
}
}
Don't forget to add the adapter to your Moshi instance.
val moshi = Moshi.Builder().add(Account.ADAPTER).add(KotlinJsonAdapterFactory()).build()
val adapter = moshi.adapter(Account::class.java)