i have one difficult to parse one jsonObject to data class object, I need that one list of this object:
data class DataClassExample(val mandatory: Boolean,
val name: String,
val regex: String?,
val regex_check: Boolean)
and I have this json object where each list object I need transform in one single list of the data class object:
{
"defaultParameters": [
{
"name": "business",
"mandatory": true,
"type": "String",
"regex": "",
"regex_check": true
},
{
"name": "environment",
"mandatory": true,
"type": "String",
"regex": "",
"regex_check": true
}
],
"userParameters": [
{
"name": "person_id",
"mandatory": true,
"type": "String",
"regex": "",
"regex_check": true
} ]
I will filter by objectName, for example "defaultParameters", and convert the list in the data class, my expected result is:
listOf(DataClassExample(name = "", mandatory = true, type = "String", regex = "", ...), DataClassExample(...))
I tryed get this value using this code:
val response = allowList.filterKeys {
it == "defaultParameters"
} as MutableMap<String, String>
but I dont now how transform this code in data class list.
Tks
2
Answers
I can recommend a 3rd party library call Klaxon
Import it with adding this to your Gradle file:
If your list is:
The Parsing line would be:
You probably want to pull in a Serialization library, for example Kotlin Serialization
It’s unclear if you’re trying to only serialize/deserialize a subset of the json, if so you’ll need to parse it first.
Here’s an example deserializing the entire
data
.We’ll use the Serializable annotations.
Let’s create a
data class
to hold both default and user params:And deserialzing to object: