This can be done without GSON or any other third party library:
@Throws(JSONException::class)
fun JSONObject.toMap(): Map<String, Any> {
val map = mutableMapOf<String, Any>()
val keysItr: Iterator<String> = this.keys()
while (keysItr.hasNext()) {
val key = keysItr.next()
var value: Any = this.get(key)
when (value) {
is JSONArray -> value = value.toList()
is JSONObject -> value = value.toMap()
}
map[key] = value
}
return map
}
@Throws(JSONException::class)
fun JSONArray.toList(): List<Any> {
val list = mutableListOf<Any>()
for (i in 0 until this.length()) {
var value: Any = this[i]
when (value) {
is JSONArray -> value = value.toList()
is JSONObject -> value = value.toMap()
}
list.add(value)
}
return list
}
Usage to convert JSONArray to List:
val jsonArray = JSONArray(jsonArrStr)
val list = jsonArray.toList()
Usage to convert JSONObject to Map:
val jsonObject = JSONObject(jsonObjStr)
val map = jsonObject.toMap()
More info is here
Answer from Michael Avoyan on Stack OverflowThis can be done without GSON or any other third party library:
@Throws(JSONException::class)
fun JSONObject.toMap(): Map<String, Any> {
val map = mutableMapOf<String, Any>()
val keysItr: Iterator<String> = this.keys()
while (keysItr.hasNext()) {
val key = keysItr.next()
var value: Any = this.get(key)
when (value) {
is JSONArray -> value = value.toList()
is JSONObject -> value = value.toMap()
}
map[key] = value
}
return map
}
@Throws(JSONException::class)
fun JSONArray.toList(): List<Any> {
val list = mutableListOf<Any>()
for (i in 0 until this.length()) {
var value: Any = this[i]
when (value) {
is JSONArray -> value = value.toList()
is JSONObject -> value = value.toMap()
}
list.add(value)
}
return list
}
Usage to convert JSONArray to List:
val jsonArray = JSONArray(jsonArrStr)
val list = jsonArray.toList()
Usage to convert JSONObject to Map:
val jsonObject = JSONObject(jsonObjStr)
val map = jsonObject.toMap()
More info is here
Use this code:
import com.google.gson.annotations.SerializedName
import com.google.gson.Gson
data class Array(
@SerializedName("message")
var message: String,
@SerializedName("name")
var name: String,
@SerializedName("creation")
var creation: String
)
data class Example(
@SerializedName("array")
var array: List<Array>? = null
)
private fun fromJson(json:String):Example{
return Gson().fromJson<Example>(json, Example::class.java)
}
PS: I made it with this site:http://www.jsonschema2pojo.org/
Videos
[{
"description":"My expense to others",
"items":["aaa","bbb"],
"name":"My Expense"
},
{
"description":"My expense to others","
items":["aaa","bbb"],
"name":"My Expense"
}]
Kotlin Code
val gson = GsonBuilder().create()
val Model= gson.fromJson(body,Array<GroupModel>::class.java).toList()
Gradle
implementation 'com.google.code.gson:gson:2.8.5'
I have found a solution that is actually working on Android with Kotlin for parsing JSON arrays of a given class. The solution of @Aravindraj didn't really work for me.
val fileData = "your_json_string"
val gson = GsonBuilder().create()
val packagesArray = gson.fromJson(fileData , Array<YourClass>::class.java).toList()
So basically, you only need to provide a class (YourClass in the example) and the JSON string. GSON will figure out the rest.
The Gradle dependency is:
implementation 'com.google.code.gson:gson:2.8.6'
put adds the list as an element to the JSONArray. Thats not what you want. You want your JSONArray to represent the list.
JSONArray offers a constructor for that:
val jsonArray = JSONArray(listOf(1, 2, 3))
But there is a much easier way. You don't need to worry about single properties. Just pass the whole POJO.
Let's say you have this:
class QuoteData(val id: Int, val quoteId: Int, travellerId: Int?)
class TravelerData(val userQuoteTravellers: List<QuoteData>)
val travelerData = TravelerData(listOf(QuoteData(1354, 546, null)))
You just have to pass travelerData to the JSONArray constructor:
val travelerDataJson = JSONArray(travelerData)
and it will be represented like this:
"userQuoteTravellers": [ { "id": 1354, "quoteId": 526, "travellerId": null } ]
With Dependencies
Add to your gradle:
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
Convert ArrayList to JsonArray
val jsonElements = (JsonArray) new Gson().toJsonTree(itemsArrayList)
Without Dependencies
val jsonElements = JSONArray(itemsArrayList)
You could try doing this instead:
val objectList = gson.fromJson(json, Array<SomeObject>::class.java).asList()
EDIT [14th January 2020]: You should NOT be using GSON anymore. Jake Wharton, one of the projects maintainers, suggests using Moshi, Jackson or kotlinx.serialization.
Try this, it uses object instead of Type..
measurements : List<SomeOjbect> = gson.fromJson(text, object : TypeToken<List<SomeOjbect>>() {}.type)
You need to change parameter in your fromJson() function call like following:
val weatherList: List<WeatherObject> = gson.fromJson(stringReader , Array<WeatherObject>::class.java).toList()
You need to pass Array<WeatherObject>::class.java for class type and then convert result into List. No need to change registerTypeAdapter() function call.
Check following code:
fun getWeatherObjectFromJson(jsonStr: String): List<WeatherObject> {
var stringReader: StringReader = StringReader(jsonStr)
var jsonReader: JsonReader = JsonReader(stringReader)
val gsonBuilder = GsonBuilder().serializeNulls()
gsonBuilder.registerTypeAdapter(WeatherObject::class.java, WeatherDeserializer())
val gson = gsonBuilder.create()
val weatherList: List<WeatherObject> = gson.fromJson(stringReader , Array<WeatherObject>::class.java).toList()
return weatherList
}
an alternative extension function:
inline fun <reified T> Gson.fromJson(json: String) = fromJson<T>(json, object : TypeToken<T>() {}.type)
usage:
val str ="[....]"
val list:List<WeatherObject> = Gson().fromJson<List<WeatherObject>>(str)
Instead of using List
val list: List<String> = gson.fromJson(jsonString, Array<String>::class.java).asList()
Use Map (This will parse your json data into map)
val map = gson.fromJson<Map<String, String>>(jsonString, MutableMap::class.java)
This JSON isn't array. You have to make object fot this type. It will look like this:
import com.google.gson.annotations.SerializedName
data class JsonData(
@SerializedName("0")
val x0: String,
@SerializedName("1")
val x1: String
)
Now in Your activity You can convert json to obbject:
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.google.gson.Gson
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val gson = Gson()
val json =
"""
{
"0" : "some picture",
"1" : "other picture"
}
"""
val jsonData = gson.fromJson<JsonData>(json, JsonData::class.java)
println(jsonData.x0) // some picture
println(jsonData.x1) // other picture
}
}
Now You can operate on that obcject but if You want list of string You can do it like this:
val list = arrayListOf<String>(jsonData.x0, jsonData.x1)
println(list) // [some picture, other picture]
Gson().toJson(myList) returns a String.
You should build a JSONArray and add its elements. Then add this true array. This just works:
JsonArray array = new JsonArray();
array.add("test1");
array.add("test2");
JsonObject object = new JsonObject();
object.add("arr", array);
You also seam to be messing up JSON and GSON objects. Here I just used Gson objects.
as @shkschneider pointed gson.toJson() returns string value and you are adding that string directly to your json object, You need to convert it to json array and then add it.
JSONArray jsArray = new JSONArray(Gson().toJson(myList))
var obj2 = JSONObject(obj.get("reciptDetail").toString())
obj2.remove("payment_details")
obj2.put("payment_details",jsArray)
Log.e("cash Object", obj2.toString())