2

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 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi Now I added below code.but still I got same result -- val jsonArray = JSONArray() jsonArray.put(jsObject)
It works: {"arr":["test1","test2"]}. You're just doing something that makes a toString() somewhere. BTW you seam to be messing up JSON and GSON objects.
3

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

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.