TransWikia.com

How to add ArrayList to JsonObject in Kotlin

Stack Overflow Asked by Rajitha Perera on February 15, 2021

PaymentDetails class

data class PaymentDetails(
val type:String,
val bank: String,
val branch: String,
val account_no: String,
val cheque_date:String,
val return_type:Boolean,
val cheque_no:String,
val return_cheque_no:String,
val amount:String)

Adding to Json Object

  var obj = JSONObject(myPreference!!.getJsonObject());
    Log.e("test Object add", obj.get("reciptDetail").toString())
    
    val paymentDetails : PaymentDetails = PaymentDetails(type, "", "", "","",false,"","",viewPaymentCash!!.etxt_amount.text.toString())
    myList.add(paymentDetails)
    val jsArray = 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())

Here I tried to add new Arraylist to existing JsonObject. Issue is that the final Json object is not what I am expecting. How can I solve that issue? Below I attched what I expected and what I got.

Expected

{"receiptNo":"fggff","todate":"4/12/2018","remark":"","payment_details":[{"account_no":" ","amount":"600","bank":"","branch":"","cheque_date":"","cheque_no":"","return_cheque_no":"","type":"Cash","return_type":false}]}

What I got from above code

{"receiptNo":"fggff","todate":"4/12/2018","remark":"","payment_details":"[{"account_no":"","amount":"600","bank":"","branch":"","cheque_date":"","cheque_no":"","return_cheque_no":"","type":"Cash","return_type":false}]"}

2 Answers

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.

Correct answer by shkschneider on February 15, 2021

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

Answered by karan on February 15, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP