Reputation: 1009
I'm sending a json object to a REST url as :
JSONObject loan=new JSONObject();
loan.put("clientId", "1");
loan.put("productId", "1");
Now I also have to send an array as part of the payload :
{
"clientId": 1,
"productId": 1,
"disbursementData": [
{
"expectedDisbursementDate":"21 December 2018",
"principal":2000,
"approvedPrincipal":2000
}
]
}
How do I send the array disbursementData using the JSONObject as I'm doing with the other elements
I have tried using:
JSONArray arr = new JSONArray();
arr.put("expectedDisbursementDate","21 December 2018");
arr.put("principal", "1000");
arr.put("approvedPrincipal", "1000");
loan.put("disbursementData", arr);
I get the following exception :
The method put(int, boolean) in the type JSONArray is not applicable for the arguments (String, String).
It appears my issue is with adding a name-value pair to JSONArray. Any help on how I can achieve this?
Upvotes: 2
Views: 11541
Reputation: 15423
Logic would be the same for any library but the syntax will differ. I am using thecom.google.gson
library.
Create object to be placed in the array :
JsonObject jsonObj = new JsonObject();
jsonObj.addProperty("expectedDisbursementDate", "21 December 2018");
jsonObj.addProperty("principal", "2000");
jsonObj.addProperty("approvedPrincipal", "2000");
Create the array and add the object to it :
JsonArray jsonArray = new JsonArray();
jsonArray.add(jsonObj);
Add the array to the original json object :
JsonObject loan = new JsonObject();
loan.addProperty("clientId", "1");
loan.addProperty("productId", "1");
loan.addProperty("disbursementData", jsonArray.toString());
Upvotes: 2
Reputation: 1454
You are creating JSONArray, array is not map and doesnt support put(key,value). You have to use put(int index, Object value), where index is the array index(same as array[index]). In your case the value should be the JSONObject :
{
"expectedDisbursementDate":"21 December 2018",
"principal":2000,
"approvedPrincipal":2000
}
Upvotes: 0
Reputation: 363
You have to create a JSONObject, put it in a JSONArray and then add it to your first JSONObject, try the following code:
JSONObject aux=new JSONObject();
aux.put("expectedDisbursementDate","21 December 2018");
aux.put("principal", "1000");
aux.put("approvedPrincipal", "1000");
JSONArray arr = new JSONArray();
arr.put(aux);
loan.put("disbursementData",arr);
Upvotes: 3
Reputation: 98
JSONArray implements Collection (the json.org implementation from which this API is derived does not have JSONArray implement Collection). And JSONObject has an overloaded put() method which takes a Collection and wraps it in a JSONArray (thus causing the problem). I think you need to force the other JSONObject.put() method to be used:
you try to add below line
loan.put("disbursementData", (Object)arr);
You should file a bug with the vendor, pretty sure their JSONObject.put(String,Collection) method is broken.
Upvotes: 0