简体   繁体   中英

JSONObject.toString() converts internal JSONArray as string in 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.

change your code

from

request.put("unitsummary", new JSONObject()
   .put("unitsummarydetail", fieldList));

to

request.put("unitsummary", new JSONObject()
   .put("unitsummarydetail", new JSONArray(fieldList)));

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

您可以创建一个JSON数组unitsummarydetail并将所有json对象unitummary添加到for循环中

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM