Devanand Adabaile
Devanand Adabaile

Reputation: 21

How to remove back slash ("\"") in JsonArray using Android Studio?

I am trying to Update multiple JsonObject data on server using JsonArray.

OutPut:-

["{\"stock_name\":\"1\",\"no_of_share\":\"1\",\"tranz_dt\":\"1\",\"buy_price\":\"1\"}","{\"stock_name\":\"2\",\"no_of_share\":\"2\",\"tranz_dt\":\"2\",\"buy_price\":\"2\"}","{\"stock_name\":\"3\",\"no_of_share\":\"3\",\"tranz_dt\":\"3\",\"buy_price\":\"3\"}"]

Output Code:

for (int i = 0; i < ItemModelList.size(); i++) {
    requestJson1.put("stock_name", ItemModelList.get(i).getStock_name().toString());
    requestJson1.put("no_of_share", ItemModelList.get(i).getNo_of_share().toString());
    requestJson1.put("tranz_dt", ItemModelList.get(i).getTranz_dt().toString());
    requestJson1.put("buy_price", ItemModelList.get(i).getBuy_price().toString());
   jsonArray1.put(requestJson1.toString());
}
requestJson.put("stockrow", jsonArray1.toString().replaceAll("\"", ""));

I expected result add Multiple Object using JsonArray without backslash with string.

Upvotes: 2

Views: 4300

Answers (4)

PPartisan
PPartisan

Reputation: 8231

Remove the various toString() calls that are dotted around, and create a new JSONObject to add to your array for each ItemModel (otherwise you'll just end up with one item in your array).

for (int i = 0; i < ItemModelList.size(); i++) {
    final ItemModel im = ItemModelList.get(i);
    final JSONObject o = new JsonObject();
    o.put("stock_name", im.getStock_name());
    o.put("no_of_share", im.getNo_of_share());
    o.put("tranz_dt", im.getTranz_dt());
    o.put("buy_price", im.getBuy_price());
    jonArray1.put(im);
}
requestJson.put("stockrow", jsonArray1);

Upvotes: 0

Henry
Henry

Reputation: 43738

No string replacements necessary.

Just replace

jsonArray1.put(requestJson1.toString());

by

jsonArray1.put(requestJson1)

You want an array of JSON objects, not of strings.

Upvotes: 2

Hemant Parmar
Hemant Parmar

Reputation: 3976

Replace "/" to ""

result = result.replaceAll("/","");
JSONArray jsonArray = new JSONArray(result);

Now in jsoanArray have without "/" data. For more have look this

Upvotes: 0

Mina chen
Mina chen

Reputation: 1684

"result" is JSON format string (like your OutPut) which you get.

JSONArray jsonArray = new JSONArray(result);

For example to get stock_name:

String[] stock_name;
stock_name = new String[jsonArray.length()];

for (int i = 0; i < jsonArray.length(); i++) {
     JSONObject jsonData = jsonArray.getJSONObject(i);
     stock_name[i] = jsonData.getString("stock_name");
}

Upvotes: 0

Related Questions