Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSONObject.toString() converts internal JSONArray as string in Android

Tags:

json

android

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.

like image 577
Rohit Gupta Avatar asked Mar 12 '26 23:03

Rohit Gupta


1 Answers

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

like image 151
Roja Vangapalli Avatar answered Mar 15 '26 13:03

Roja Vangapalli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!