1

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?

2 Answers 2

1

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())
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @Mayur this is working but How I can convert my object to startingJson as yours?
@IslamAhmed If you already have json object then you don't need to convert it String . Just start from initialize the array step & replace startingJsonObj with your JSON object.
I did it because i just copied it from your question as string.
0

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()
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.