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:
Answer from Willi Mentzel on Stack Overflow"userQuoteTravellers": [ { "id": 1354, "quoteId": 526, "travellerId": null } ]
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)
If I read the JSONArray constructors correctly, you can build them from any Collection (arrayList is a subclass of Collection) like so:
ArrayList<String> list = new ArrayList<String>();
list.add("foo");
list.add("baar");
JSONArray jsArray = new JSONArray(list);
References:
- jsonarray constructor: http://developer.android.com/reference/org/json/JSONArray.html#JSONArray%28java.util.Collection%29
- collection: http://developer.android.com/reference/java/util/Collection.html
Use Gson library to convert ArrayList to JsonArray.
Gson gson = new GsonBuilder().create();
JsonArray myCustomArray = gson.toJsonTree(myCustomList).getAsJsonArray();
android - How to add ArrayList to JsonObject in Kotlin - Stack Overflow
how to parse JSONArray to List<CustomObject> ?
android - Converting JSONarray to ArrayList - Stack Overflow
android - Can't convert JSONArray into a list (Kotlin) - Stack Overflow
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())
ArrayList<String> listdata = new ArrayList<String>();
JSONArray jArray = (JSONArray)jsonObject;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.getString(i));
}
}
I've done it using Gson (by Google).
Add the following line to your module's build.gradle:
dependencies {
// ...
// Note that `compile` will be deprecated. Use `implementation` instead.
// See https://stackoverflow.com/a/44409111 for more info
implementation 'com.google.code.gson:gson:2.8.2'
}
JSON string:
private String jsonString = "[\n" +
" {\n" +
" \"id\": \"c200\",\n" +
" \"name\": \"Ravi Tamada\",\n" +
" \"email\": \"[email protected]\",\n" +
" \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
" \"gender\" : \"male\",\n" +
" \"phone\": {\n" +
" \"mobile\": \"+91 0000000000\",\n" +
" \"home\": \"00 000000\",\n" +
" \"office\": \"00 000000\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"id\": \"c201\",\n" +
" \"name\": \"Johnny Depp\",\n" +
" \"email\": \"[email protected]\",\n" +
" \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
" \"gender\" : \"male\",\n" +
" \"phone\": {\n" +
" \"mobile\": \"+91 0000000000\",\n" +
" \"home\": \"00 000000\",\n" +
" \"office\": \"00 000000\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"id\": \"c202\",\n" +
" \"name\": \"Leonardo Dicaprio\",\n" +
" \"email\": \"[email protected]\",\n" +
" \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
" \"gender\" : \"male\",\n" +
" \"phone\": {\n" +
" \"mobile\": \"+91 0000000000\",\n" +
" \"home\": \"00 000000\",\n" +
" \"office\": \"00 000000\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"id\": \"c203\",\n" +
" \"name\": \"John Wayne\",\n" +
" \"email\": \"[email protected]\",\n" +
" \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
" \"gender\" : \"male\",\n" +
" \"phone\": {\n" +
" \"mobile\": \"+91 0000000000\",\n" +
" \"home\": \"00 000000\",\n" +
" \"office\": \"00 000000\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"id\": \"c204\",\n" +
" \"name\": \"Angelina Jolie\",\n" +
" \"email\": \"[email protected]\",\n" +
" \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
" \"gender\" : \"female\",\n" +
" \"phone\": {\n" +
" \"mobile\": \"+91 0000000000\",\n" +
" \"home\": \"00 000000\",\n" +
" \"office\": \"00 000000\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"id\": \"c205\",\n" +
" \"name\": \"Dido\",\n" +
" \"email\": \"[email protected]\",\n" +
" \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
" \"gender\" : \"female\",\n" +
" \"phone\": {\n" +
" \"mobile\": \"+91 0000000000\",\n" +
" \"home\": \"00 000000\",\n" +
" \"office\": \"00 000000\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"id\": \"c206\",\n" +
" \"name\": \"Adele\",\n" +
" \"email\": \"[email protected]\",\n" +
" \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
" \"gender\" : \"female\",\n" +
" \"phone\": {\n" +
" \"mobile\": \"+91 0000000000\",\n" +
" \"home\": \"00 000000\",\n" +
" \"office\": \"00 000000\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"id\": \"c207\",\n" +
" \"name\": \"Hugh Jackman\",\n" +
" \"email\": \"[email protected]\",\n" +
" \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
" \"gender\" : \"male\",\n" +
" \"phone\": {\n" +
" \"mobile\": \"+91 0000000000\",\n" +
" \"home\": \"00 000000\",\n" +
" \"office\": \"00 000000\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"id\": \"c208\",\n" +
" \"name\": \"Will Smith\",\n" +
" \"email\": \"[email protected]\",\n" +
" \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
" \"gender\" : \"male\",\n" +
" \"phone\": {\n" +
" \"mobile\": \"+91 0000000000\",\n" +
" \"home\": \"00 000000\",\n" +
" \"office\": \"00 000000\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"id\": \"c209\",\n" +
" \"name\": \"Clint Eastwood\",\n" +
" \"email\": \"[email protected]\",\n" +
" \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
" \"gender\" : \"male\",\n" +
" \"phone\": {\n" +
" \"mobile\": \"+91 0000000000\",\n" +
" \"home\": \"00 000000\",\n" +
" \"office\": \"00 000000\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"id\": \"c2010\",\n" +
" \"name\": \"Barack Obama\",\n" +
" \"email\": \"[email protected]\",\n" +
" \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
" \"gender\" : \"male\",\n" +
" \"phone\": {\n" +
" \"mobile\": \"+91 0000000000\",\n" +
" \"home\": \"00 000000\",\n" +
" \"office\": \"00 000000\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"id\": \"c2011\",\n" +
" \"name\": \"Kate Winslet\",\n" +
" \"email\": \"[email protected]\",\n" +
" \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
" \"gender\" : \"female\",\n" +
" \"phone\": {\n" +
" \"mobile\": \"+91 0000000000\",\n" +
" \"home\": \"00 000000\",\n" +
" \"office\": \"00 000000\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"id\": \"c2012\",\n" +
" \"name\": \"Eminem\",\n" +
" \"email\": \"[email protected]\",\n" +
" \"address\": \"xx-xx-xxxx,x - street, x - country\",\n" +
" \"gender\" : \"male\",\n" +
" \"phone\": {\n" +
" \"mobile\": \"+91 0000000000\",\n" +
" \"home\": \"00 000000\",\n" +
" \"office\": \"00 000000\"\n" +
" }\n" +
" }\n" +
" ]";
ContactModel.java:
public class ContactModel {
public String id;
public String name;
public String email;
}
Code for converting a JSON string to ArrayList<Model>:
Note: You have to import java.lang.reflect.Type;:
// Top of file
import java.lang.reflect.Type;
// ...
private void parseJSON() {
Gson gson = new Gson();
Type type = new TypeToken<List<ContactModel>>(){}.getType();
List<ContactModel> contactList = gson.fromJson(jsonString, type);
for (ContactModel contact : contactList){
Log.i("Contact Details", contact.id + "-" + contact.name + "-" + contact.email);
}
}
Hope this will help you.
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
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/
[{
"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'
It's an ugly request, and you might be able to resolve it with an ugly solution :)
I wouldn't suggest this for anything serious, large, or anything that requires some hard and complex maintenance, but if this object will stay that simple (one int and two strings, non-nullable fields) and won't change a lot, you can do it manually:
class RailPoint(
var railPointId: Int,
var startTime: String,
var endTime: String
)
val rails = listOf(
RailPoint(1, "", "2021-10-19 07:37:19"),
RailPoint(2, "2021-10-19 07:33:37", "2021-10-19 07:35:20"),
)
fun toJson(rails: List<RailPoint>): String {
val sb = StringBuilder()
rails.forEachIndexed { index, railPoint ->
sb.append("\"railPoint[$index][railPointId]\": ${railPoint.railPointId},")
sb.append("\"railPoint[$index][startTime]\": \"${railPoint.startTime}\",")
sb.append("\"railPoint[$index][endTime]\": \"${railPoint.endTime}\",")
}
return "{ $sb }"
}
It is very dirty approach, but might be enough, as long as you don't make RailPoint more complex, especially, if you don't add members that are custom classes or collections.
(I assumed that times are Strings, but if they are not, just add some date formatting in the formula)
This can be solved by first having Gson serialize the list to a JsonArray, then combining the elements in a new JsonObject and afterwards serializing that object to JSON:
val rails: List<RailPoint> = ...
val gson = Gson()
val railsJsonList = gson.toJsonTree(rails).asJsonArray!!
val railsJsonObject = JsonObject()
// Transform elements
for (i in 0 until railsJsonList.size()) {
val railPointJson = railsJsonList[i].asJsonObject
for ((name, value) in railPointJson.entrySet()) {
railsJsonObject.add("railPoint[$i][$name]", value)
}
}
println(gson.toJson(railsJsonObject))
public class Semester {
private static final String JSON_ID = "id";
private static final String JSON_TITLE = "title";
private static final String JSON_CREDITS = "credits";
private static final String JSON_GPA = "gpa";
private static final String JSON_CUMULATIVECREDITS = "cumulativecredits";
private static final String JSON_CUMULATIVEGPA = "cumulativegpa";
private static final String JSON_COURSES = "courses";
private UUID id;
private String title;
private int credits;
private double GPA;
private int cumulativeCredits;
private double cumulativeGPA;private ArrayList<Course> courses;
public Semester() {
id = UUID.randomUUID();
courses = new ArrayList<Course>();
for (int i = 0; i < 6; i++) {
courses.add(new Course());
}
}
public Semester(JSONObject json) throws JSONException {
id = UUID.fromString(json.getString(JSON_ID));
title = json.getString(JSON_TITLE);
credits = json.getInt(JSON_CREDITS);
GPA = json.getDouble(JSON_GPA);
cumulativeCredits = json.getInt(JSON_CUMULATIVECREDITS);
cumulativeGPA = json.getDouble(JSON_CUMULATIVEGPA);//what do i put here?
}
public JSONObject toJSON() throws JSONException {
JSONObject json = new JSONObject();
json.put(JSON_ID, id.toString());
json.put(JSON_TITLE, title);
json.put(JSON_CREDITS, credits);
json.put(JSON_GPA, GPA);
json.put(JSON_CUMULATIVECREDITS, cumulativeCredits);
json.put(JSON_CUMULATIVEGPA, cumulativeGPA);JSONArray array = new JSONArray(courses);
json.put(JSON_COURSES, array);
return json; } .........
This is followed by a bunch of getters and setters for each private variable.
The first bolded item is the private ArrayList of a custom class that I made.
The second bolded item is what I need help with: how to retrieve the custom ArrayList just like the other variables.
Lastly, the third bolded item is my current idea of how to put an ArrayList into a JSONObject, but I don't know how to retrieve it. If there is another way, please tell me. Thank you.