Im trying to map a json to a data class in kotlin
JSON :
{
"TimeZones": [
{
"MapZone": {
"Other": "Afghanistan Standard Time",
"Type": "Asia/Kabul",
"Territory": "001"
}
}
]
}
my data TimeZones.kt class
data class TimeZones (
#Expose var TimeZones: List<MapZone>? = null
)
data class MapZone (
#Expose var Other: String? = null,
#Expose var Type: String? = null,
#Expose var Territory: String? = null
)
but when I run this code the mapzone attribute values are always null
Gson().fromJson(Utils.readJSONFroRaw(), TimeZones::class.java)
I want to map this properly
You are missing one level of the structure:
data class TimeZones (
#Expose var TimeZones: List<TimeZone>? = null
)
data class TimeZone (
#Expose var MapZone: MapZone? = null
)
data class MapZone (
#Expose var Other: String? = null,
#Expose var Type: String? = null,
#Expose var Territory: String? = null
)
Related
I'm trying to assign a string value to an string attribute part of a data class object and it's not working:
appointmentInfo.mySymptoms?.medsDescription = "string description"
where,
data class AppointmentInfo(var id : Int? = null,
var planType : String? = null,
var dateFormat : DateFormat,
var mySymptoms : MySymptoms? = null) : Parcelable
#Parcelize
data class MySymptoms(var grantAccess : Boolean,
var takingMeds : Boolean,
var medsDescription : String? = null,
var symptomList : List<String>? = null,
var symptomsDescription : String? = null,
var generalDescription : String? = null ```
**appointmentInfo.mySymptoms?.medsDescription is always null**
Make sure the variables are assigned properly.
Code
data class AppointmentInfo(
var mySymptoms : MySymptoms? = null,
)
data class MySymptoms(
var medsDescription : String? = null,
)
fun main() {
var appointmentInfo = AppointmentInfo()
appointmentInfo.mySymptoms = MySymptoms()
appointmentInfo.mySymptoms?.medsDescription = "string description"
println(appointmentInfo.mySymptoms?.medsDescription)
}
Output
string description
Kotlin Playground link
You should use copy() function of data class https://kotlinlang.org/docs/data-classes.html#copying as Jet Brains suggests all data class member should be read only val
I've a realm class A in my android project -
open class A(
var id: Int? = null,
var level: String? = null,
var state: String? = null,
var updated_at: String? = null,
var created_at: String? = null,
var person: Person? = null
): RealmObject()
and Person -
open class Person(
var id: Int? = null,
var name: String? = null,
var email: String? = null,
var url: String? = null
): RealmObject()
I can retrieve list of items of class A sorted by Class A's id attribute -
fun getItemsOfA() : List<A> {
val listToBeReturn: MutableList<A> = mutableListOf()
DBManager.getRealm().executeTransection { realm ->
val tempList = realm.where(A::class.java).sort("id").findAll()
for (item in tempList) {
listToBeReturn.add(item)
}
And I'm getting sorted list. But I want to have a sorted list by the Person's id attribute instead of A's id. Any insight on this.
How can I achieve these?
Thanks & Regards
I have issue when using Klaxon 5.5
Class :
data class QRResponse(
#field:SerializedName("qrType")
val qrType: String? = null,
#field:SerializedName("qrData")
val qrData: String? = null
)
Code :
val dataContents = result.contents
Log.d("ScanQRData", "result.contents : $dataContents")
val dataQR = Klaxon().parse<QRResponse>(dataContents)
Log.d("ScanQRData", "dataQR : $dataQR")
Result :
ScanQRData: result.contents : {"qrType": "product", "qrData":"352307811"}
ScanQRData: dataQR : QRResponse(qrType=null, qrData=null)
Any suggestion what happened to qrType and qrData null after parse from Klaxon?
Klaxon doesn't process #field:SerializedName annotation (where you have imported it from?). The correct way to customize mapping between your JSON documents and Kotlin objects in Klaxon is #Json annotation:
data class QRResponse(
#Json(name = "qrType")
val qrType: String? = null,
#Json(name = "qrData")
val qrData: String? = null
)
I have a probleme right now.
I'm trying to fetch data from an api rest WebSite Url, i've made all the things i was needed to do, but it doesn't working.
I don't know what is this problem, thank's for helping me
Error : Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 75 path $.data
AllClass.kt
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
class ClassVal {
#SerializedName("pagination")
#Expose
var pagination: Pagination? = null
#SerializedName("data")
#Expose
var data: Data? = null
}
class Pagination {
#SerializedName("limit")
#Expose
var limit: Int? = null
#SerializedName("count")
#Expose
var count: Int? = null
}
class Data {
#SerializedName("author")
#Expose
val author: String? = null
#SerializedName("title")
#Expose
val title: String? = null
#SerializedName("description")
#Expose
val description: String? = null
#SerializedName("url")
#Expose
val url: String? = null
#SerializedName("source")
#Expose
val source: String? = null
#SerializedName("image")
#Expose
val image: String? = null
#SerializedName("category")
#Expose
val category: String? = null
#SerializedName("language")
#Expose
val language: String? = null
#SerializedName("country")
#Expose
val country: String? = null
#SerializedName("published_at")
#Expose
val published: String? = null
}
ClassValApi.kt
import retrofit2.Call
import retrofit2.http.GET
interface ClassValApi {
#GET("v1/news?access_key=EnterKey")
fun getNews() : Call<ClassVal>
}
MainActivity
fun getClassValApi() {
val retro = Retro().getRetroClientInstance().create(ClassValApi::class.java)
retro.getNews().enqueue(object : Callback<ClassVal> {
override fun onResponse(call: Call<ClassVal>, response: Response<ClassVal>) {
val news = response.body().toString()
Log.i("bon voila", news)
}
override fun onFailure(call: Call<ClassVal>, t: Throwable) {
Log.e("Failed", t.message.toString())
}
})
}
Json Code exemple
Yes i have an exemple : {"pagination":
{"limit":25,"offset":0,"count":25,"total":13339023},"data":
[{"author":"Reuters","title":"Guinea\u2019s Conde wins presidency with 59.5%
of vote -election commission","description":"CONAKRY \u0026#8212; President
Alpha Conde of Guinea won the Oct. 18 election with 59.5% of the vote,
according to a full preliminary tally from the election commission on
Saturday. The victory, which requires confirmation by the Constitutional
Court, gives a third term in office to the 82-year-old Conde after a bitterly
fought election in which[\u0026#8230;]","url":"https:\/\/nationalpost.com\/pmn\/news-pmn\/guineas-conde-wins-presidency-with-59-5-of-vote-election-commission","source":"nationalpost","image":null,"category":"general","language":"en","country":"us","published_at":"2020-10-24T13:53:58+00:00"}
In provided JSON data field is a JSONArray, not a JSONObject, so you need to change
var data: Data? = null
to something like:
var data: List<Data>? = null
I have the following data class in Kotlin:
import com.google.gson.annotations.SerializedName
data class RouteGroup(
#SerializedName("name") var name: String,
#SerializedName("id") var id: Int
)
Sometimes I need to create an object with both fields, sometimes with only one of them.
How can I do this?
EDIT
This is not the duplicate of this question: Can Kotlin data class have more than one constructor?
That question shows how to set a default value for a field. But in my case, I don't need to serialize the field with the default value. I want a field to be serialized only when I explicitly assign a value to it.
it is easy you have to use the nullable operator
import com.google.gson.annotations.SerializedName
data class RouteGroup #JvmOverloads constructor(
#SerializedName("name") var name: String? = null,
#SerializedName("id") var id: Int? = null
)
You may need something like this:
sealed class RouteGroup
data class RouteGroupWithName(
#SerializedName("name") var name: String
) : RouteGroup()
data class RouteGroupWithId(
#SerializedName("id") var id: Int
) : RouteGroup()
data class RouteGroupWithNameAndId(
#SerializedName("name") var name: String,
#SerializedName("id") var id: Int
) : RouteGroup()
EDIT 1:
Or you can use nullable fields and named parameters like this:
data class RouteGroup(
#SerializedName("name") var name: String? = null,
#SerializedName("id") var id: Int? = null
)
val routeGroupWithName = RouteGroup(name = "example")
val routeGroupWithId = RouteGroup(id = 2)
val routeGroupWithNameAndId = RouteGroup(id = 2, name = "example")