skip to Main Content

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


  1. I can recommend a 3rd party library call Klaxon

    Import it with adding this to your Gradle file:

    dependencies {
        implementation 'com.beust:klaxon:5.5'
        ...
    }
    

    If your list is:

    val data = """[
                {
                  "name": "business",
                  "mandatory": true,
                  "type": "String",
                  "regex": "",
                  "regex_check": true
                },
                {
                  "name": "environment",
                  "mandatory": true,
                  "type": "String",
                  "regex": "",
                  "regex_check": true
                }
             ]"""
    

    The Parsing line would be:

    Klaxon().parseArray<DataClassExample>(data)
    
    Login or Signup to reply.
  2. 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:

    @Serializable
    data class AllParameters(
        val defaultParameters: List<Parameters>,
        val userParameters: List<Parameters>
    )
    
    @Serializable
    data class Parameters(
        val mandatory: Boolean,
        val name: String,
        val type: String,
        val regex: String?,
        @SerialName("regex_check")
        val regexCheck: Boolean
    )
    

    And deserialzing to object:

    val obj = Json.decodeFromString<AllParameters>(data)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search