I am creating a JSON request as followed:
JSONObject request = new JSONObject();
request.put("ID", "35");
request.put("password", "password");
List<JSONObject> fieldList = new ArrayList<>();
for (int i = 0; i < 3; i++) {
fieldList.add(new JSONObject()
.put("unitid", "unitid " + i)
.put("price", "Price " + i));
}
request.put("unitsummary", new JSONObject()
.put("unitsummarydetail", fieldList)
);
String requestString = request.toString();
The value of requestString variable should be :
{
"ID": "35",
"password": "password",
"unitsummary": {
"unitsummarydetail": [
{
"price": "Price 0",
"unitid": "unitid 0"
},
{
"price": "Price 1",
"unitid": "unitid 1"
},
{
"price": "Price 2",
"unitid": "unitid 2"
}
]
}
}
But it is :
{
"ID": "35",
"password": "password",
"unitsummary": {
"unitsummarydetail": "[{\"unitid\":\"unitid 0\",\"price\":\"Price 0\"}, {\"unitid\":\"unitid 1\",\"price\":\"Price 1\"}, {\"unitid\":\"unitid 2\",\"price\":\"Price 2\"}]"
}
}
It is converting the unitsummarydetail as string.
I have tried but didn't find similar issue or any solution on internet.
Is there any issue in my code or this is the behavior of library?
Any ideas or solution code snippets are welcome.
Thanks.
Use JSONArray instead of ArrayList.
JSONObject request = new JSONObject();
request.put("ID", "35");
request.put("password", "password");
JSONArray fieldList = new JSONArray();
for (int i = 0; i < 3; i++) {
fieldList.put(new JSONObject() .put("unitid", "unitid " + i) .put("price", "Price " + i));
}
request.put("unitsummary", new JSONObject() .put("unitsummarydetail", fieldList) );
String requestString = request.toString();
Output:
{"ID":"35","password":"password","unitsummary":{"unitsummarydetail":[{"unitid":"unitid 0","price":"Price 0"},{"unitid":"unitid 1","price":"Price 1"},{"unitid":"unitid 2","price":"Price 2"}]}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With