Skip to content Skip to sidebar Skip to footer

Create An Array Of Json Objects

I need to create a JSON Object for an Arraylist. Below is the code public boolean submitOrder(ArrayList orderList) { serUri = 'lists.json';

Solution 1:

Your JSONObject json = new JSONObject(); should be within the loop.

Additionally, you should not do a get(i) each time to access properties (for performance). You can use the other construct of the for loop:

for (OrderDetailsData data : orderList) {
  JSONObject json = newJSONObject();
  json.put("orderno", data.getOrderNumber().toString());
  // ...
}

Finally, maybe you should consider having a function that reads/writes a JSON object from an OrderDetailsData so that you can reuse the code in other webservices.

Solution 2:

Small mistake

try {
            for (int i = 0; i < orderList.size(); i++) {

                JSONObject json = new JSONObject(); // update here

                json.put("orderno", orderList.get(i).getOrderNumber()
                        .toString());
                json.put("tableno", orderList.get(i).getTableNumber()
                        .toString());
                json.put("itemname", orderList.get(i).getItemName().toString());
                json.put("amount", orderList.get(i).getAmount().toString());

                json.put("ordstatus", orderList.get(i).getOrderStatus()
                        .toString());
                array.put(json);



            }

         catch (JSONException je) {
            returnfalse;
        }

Solution 3:

Look at this I'm trying to use GSON lib, try out this, I'm not tested. This should work fine.

From Json string to Json object this way:

StringjsonStr="{\"a\": \"A\"}";

Gsongson=newGson();
JsonElementelement= gson.fromJson (jsonStr, JsonElement.class);
JsonObjectjsonObj= element.getAsJsonObject();

For your code this should work fine:

publicbooleansubmitOrder(ArrayList<OrderDetailsData> orderList) 
{
    serUri = "lists.json";
    method = "post";

    Gsongson=newGson();
    Stringjsonstr=newGson().toJson(orderList);
    JsonElementelement= gson.fromJson (jsonStr, JsonElement.class);
    JsonObjectjsonObject= element.getAsJsonObject();

    WebServiceAsyncTaskwebServiceTask=newWebServiceAsyncTask();
    webServiceTask.execute(serUri, method,jsonObject, this);
    returntrue;
}

Solution 4:

This following snippet will create array of json objects in single statement, it even performs null checks while creating json from object using Google's Gson library.

publicbooleansubmitOrder(ArrayList<OrderDetailsData> orderList) {
    Gsongson=newGson();
    JsonObjectmyObj=newJsonObject();

    JsonElementordersObj= gson.toJsonTree(orderList);
    myObj.add("list", ordersObj);
}

Solution 5:

You need to instantiate the json object inside the for loop.

Post a Comment for "Create An Array Of Json Objects"