I need to create a JSON Object for an Arraylist. Below is the code
public boolean submitOrder(ArrayList orderList) {
serUri
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:
String jsonStr = "{\"a\": \"A\"}";
Gson gson = new Gson();
JsonElement element = gson.fromJson (jsonStr, JsonElement.class);
JsonObject jsonObj = element.getAsJsonObject();
For your code this should work fine:
public boolean submitOrder(ArrayList<OrderDetailsData> orderList)
{
serUri = "lists.json";
method = "post";
Gson gson = new Gson();
String jsonstr = new Gson().toJson(orderList);
JsonElement element = gson.fromJson (jsonStr, JsonElement.class);
JsonObject jsonObject = element.getAsJsonObject();
WebServiceAsyncTask webServiceTask = new WebServiceAsyncTask();
webServiceTask.execute(serUri, method,jsonObject, this);
return true;
}
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.
public boolean submitOrder(ArrayList<OrderDetailsData> orderList) {
Gson gson = new Gson();
JsonObject myObj = new JsonObject();
JsonElement ordersObj = gson.toJsonTree(orderList);
myObj.add("list", ordersObj);
}
You need to instantiate the json object inside the for loop.
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 = new JSONObject();
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.
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) {
return false;
}