Reputation: 736
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
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
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