Islam Ahmed
Islam Ahmed

Reputation: 736

How to convert object of map into array of objects?

I have this json object

{
"107": "First",
"125": "Second",
"130": "Third",
"141": "Fourth"
}

I want to convert it into array of objects like this

[
  {
  "107":"First"
  },
  {
  "125":"Second"
  },
  {
  "130":"Third"
  },
  {
  "141":"Fourth"
  }
]

To be easy to extract each object in the form of Array.

How can I do this by kotlin?

Upvotes: 1

Views: 823

Answers (2)

Mayur Gajra
Mayur Gajra

Reputation: 9073

You can do it as following, read inline comments to understand:

//your starting JSON string
        val startingJson = "{\n" +
                "\"107\": \"First\",\n" +
                "\"125\": \"Second\",\n" +
                "\"130\": \"Third\",\n" +
                "\"141\": \"Fourth\"\n" +
                "}"

        //your starting JSON object
        val startingJsonObj = JSONObject(startingJson)

        //initialize the array
        val resultJsonArray = JSONArray()

        //loop through all the startingJsonObj keys to get the value
        for (key in startingJsonObj.keys()) {
            val resultObj = JSONObject()
            val value = startingJsonObj.opt(key)
            //put values in individual json object
            resultObj.put(key, value)
            //put json object into the final array
            resultJsonArray.put(resultObj)
        }

        Log.d("resultJsonArray", resultJsonArray.toString())

Upvotes: 1

isthemartin
isthemartin

Reputation: 126

This can help you using Gson():

data class MyData {
    var number: String,
    var name: String
}

//You can use jsonValue as String too
fun convertJsonToArray(jsonValue: JsonObject) {
    val myDataArray = Gson().fromJson(jsonValue, Array<MyData>::class.java)
//if you need it as list
    myDataArray.toList()
}

Upvotes: 0

Related Questions