如何在Kotlin中将ArrayList添加到JsonObject

时间:2018-12-04 08:51:59

标签: android kotlin

  

PaymentDetails类

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)
  

添加到Json对象

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

在这里,我尝试将新的Arraylist添加到现有的JsonObject。问题是最终的Json对象不是我期望的。我该如何解决这个问题?在下面,我提出了我的期望和所得到的。谢谢进阶

预期

{"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}]}

我从上面的代码中得到了什么

{"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 个答案:

答案 0 :(得分:2)

Gson().toJson(myList)返回一个String

您应该构建一个JSONArray并添加其元素。然后添加此真实数组。这样就可以了:

JsonArray array = new JsonArray();
array.add("test1");
array.add("test2");
JsonObject object = new JsonObject();
object.add("arr", array);

您还希望弄乱JSON和GSON对象。在这里,我只使用了Gson对象。

答案 1 :(得分:1)

@shkschneider指出gson.toJson()返回字符串值,并且您正在将该字符串直接添加到json对象,您需要将其转换为json数组,然后添加。

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