Remove a Jsonobject based on some key-value from JsonArray android - android

I am working on an android application and somewhere in my application, I want to remove some JsonObject from jsonArray. Below is the JsonArray:
[
{
"id": 2,
"image": "http://devaddons1.socialengineaddons.com/mobiledemotesting/public/system/e0/39/01/137a8_8640.png?c=279d",
},
{
"id": 4,
"image": "http://devaddons1.socialengineaddons.com/mobiledemotesting/public/system/5f/3a/01/13826_c4c9.png?c=ff74",
},
{
"id": 1,
"image": "http://devaddons1.socialengineaddons.com/mobiledemotesting/public/system/ac/39/01/13774_7183.png?c=35ee",
},
{
"id": 5,
"image": "http://devaddons1.socialengineaddons.com/mobiledemotesting/public/system/a7/3a/01/1386e_d5c5.png?c=3f1e",
},
{
"id": 3,
"image": "http://devaddons1.socialengineaddons.com/mobiledemotesting/public/system/1d/3a/01/137e4_e803.png?c=9ab9",
},
{
"id": 6,
"image": "http://devaddons1.socialengineaddons.com/mobiledemotesting/public/system/cf/3a/01/13896_edab.png?c=1e7b",
}
]
Now from this JsonArray, I want to remove JsonObject which is having id equals to 2.
How can I do this, I want to optimize this code because, I can do it using a for loop, but I do not want to do it using for loop.
Is there any other way to do it. Please help me if anyone know about this.
Thanks a lot in advanced.

Assuming that you are using JsonArray from Gson library, you can use remove() method.
For example:
int idToRemove = 3;
JsonElement elementToRemove = null;
for(JsonElement e : jsonArray) {
JsonObject o = e.getAsJsonObject();
if(o.get("id").getAsInt() == idToRemove) {
elementToRemove = e;
break;
}
}
if (elementToRemove != null) jsonArray.remove(elementToRemove);
Alternatively, use Iterator<JsonElement> explicitly.

JSONArray jsonArray = new JSONArray(string);
int len = jsonArray.length();
int position = -1;
int wantedID = 2;
for (int i=0;i<len;i++){
JSONObject jsonObj = jsonArray.getJSONObject(i);
int id = Integer.parseInt(jsonObj.get("id"));
if (id == wantedID) {
position = i;
break;
}
}
JSONArray jsonArray_out = jsonArray;
if (position >= 0) {
//for 19 API use this: jsonArray_out.remove(position);
//or remove using this code:
jsonArray_out = remove(position, jsonArray);
}
String out = jsonArray_out.toString();
Using this methods you can remove data from JSON:
https://stackoverflow.com/a/12526047/1979882
public static JSONArray remove(final int idx, final JSONArray from) {
final List<JSONObject> objs = asList(from);
objs.remove(idx);
final JSONArray ja = new JSONArray();
for (final JSONObject obj : objs) {
ja.put(obj);
}
return ja;
}
public static List<JSONObject> asList(final JSONArray ja) {
final int len = ja.length();
final ArrayList<JSONObject> result = new ArrayList<JSONObject>(len);
for (int i = 0; i < len; i++) {
final JSONObject obj = ja.optJSONObject(i);
if (obj != null) {
result.add(obj);
}
}
return result;
}
or this:
https://stackoverflow.com/a/20250881/1979882

Related

nested JSON object inside JSON array

I'm trying to parse a JSON object. The JSON response is as follows.
{
"message": "Success",
"list": [
{
"orderId": 24,
"phoneNumber": "1234567893",
"totalAmount": 100,
"addressBean": {
"cadId": 1,
"phone2": "1234567899",
"address1": "34, gandhi nagar",
}
},
Android code which i have tried for getting "orderId", "phoneNumber" and "totalAmount" is below.
final List<OrderModel> orderList = new ArrayList<>();
public void onResponse(JSONObject response) {
try {
if (response.getString("message").equalsIgnoreCase("Success")) {
JSONArray jArray = response.getJSONArray("list");
for (int i = 0; i < jArray.length(); i++) {
OrderModel model = new OrderModel();
orderModel.setOrderId(jArray.getJSONObject(i).getString("orderId"));
orderModel.setphoneNumber(jArray.getJSONObject(i).getString("phoneNumber"));
orderModel.setTotalAmount(new BigDecimal(jArray.getJSONObject(i).getString("totalAmount")));
orderList.add(orderModel);
}
setOrderList(orderList);
I want to show the "cadId", "phone2" and "address1" in a Textview. How can i do that?
Try to use this Code
try {
JSONArray jArray = response.getJSONArray("list");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
if (jsonObject.has("addressBean")){
JSONObject addressObject = jsonObject.getJSONObject("addressBean");
int cadId = addressObject.getInt("cadId");
String phone = addressObject.getString("phone2");
String address = addressObject.getString("address1");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Code for phone2
String phone2 = jArray.getJSONObject(i).getJSONObject("addressBean").getString("phone2");
Use getInt() for cadId

Android : parse a JSONArray

I would need help to parse this JSONArray in my Android app. I'm a bit confused with JSONObjects and JSONArrays :
[
{
"nid": [
{
"value": "3"
}
],
"uid": [
{
"target_id": "1",
"url": "/user/1"
}
],
"field_image": [
{
"target_id": "2",
"alt": "alternate 1",
"title": "",
"width": "640",
"height": "640",
"url": "http://url"
},
{
"target_id": "3",
"alt": "alternate 2",
"title": "",
"width": "640",
"height": "640",
"url": "http://url"
}
]
}]
Here is what I've got to start the iteration :
public void onResponse(JSONArray response) {
try {
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
...
Here is your code to parse data,
private void parseData(){
try {
JSONArray jsonArray=new JSONArray(response);
JSONObject jsonObject=jsonArray.getJSONObject(0);
JSONArray jsonArrayNid=jsonObject.getJSONArray("nid");
JSONArray jsonArrayUid=jsonObject.getJSONArray("uid");
JSONArray jsonArrayField_image=jsonObject.getJSONArray("field_image");
for(int i=0;i<jsonArrayNid.length();i++){
JSONObject jsonObjectNid=jsonArrayNid.getJSONObject(i);
String value=jsonObjectNid.getString("value"); //here you get your nid value
}
for(int i=0;i<jsonArrayUid.length();i++){
JSONObject jsonObjectUid=jsonArrayUid.getJSONObject(i);
String target_id=jsonObjectUid.getString("target_id"); //here you get your uid target_id value
String url=jsonObjectUid.getString("url"); //here you get your uid url value
}
for(int i=0;i<jsonArrayField_image.length();i++){
JSONObject jsonObjectFieldImage=jsonArrayField_image.getJSONObject(i);
String target_id=jsonObjectFieldImage.getString("target_id");
String alt=jsonObjectFieldImage.getString("alt");
String title=jsonObjectFieldImage.getString("title");
String width=jsonObjectFieldImage.getString("width");
String height=jsonObjectFieldImage.getString("height");
String url=jsonObjectFieldImage.getString("url");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
for (int i = 0; i < response.length(); i++) {
JSONObject tobject = response.getJSONObject(i);
JSONArray nid = tobject.getJSONArray("nid");
JSONArray uid= tobject.getJSONArray("uid");
JSONArray field_image= tobject.getJSONArray("field_image");
//similarly you can loop inner jsonarrays
}
Use code according to you:
JSONArray array = null;
try {
array = new JSONArray(url); // your web url
JSONObject object = array.getJSONObject(0);
JSONArray array1 = object.getJSONArray("nid");
JSONObject object1 = array1.getJSONObject(0);
String value = object1.getString("value");
JSONArray array2 = object.getJSONArray("uid");
JSONObject object2 = array2.getJSONObject(0);
String target = object2.getString("target_id");
String url = object2.getString("url");
JSONArray array3 = object.getJSONArray("field_image");
JSONObject object3 = array3.getJSONObject(0);
String alt = object3.getString("alt");
Toast.makeText(Testing.this,value+"\n"+target+"\n"+url+"\n"+alt,Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
Try to parse like this.
In this code, jsonArray is the parent array which you have in your JSON.
for(int i=0;i<jsonArray.length();i++)
{
try {
JSONObject object=jsonArray.getJSONObject(i);
JSONArray imageArray=object.getJSONArray("field_image");
for(int j=0;j<imageArray.length();j++)
{
JSONObject imageObject=imageArray.getJSONObject(j);
String targetId=imageObject.getString("target_id");
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
Now :) if you have to parse something first look for some library:
http://www.java2s.com/Code/Jar/g/Downloadgson222jar.htm
Download gson.jar and then create java classes that mimic your desired json:
class C1{
private String value;
}
class C2{
private String target_id;
private String url;
}
class C3{
private String target_id;
private String alt;
private String title;
private String width;
private String height;
private String url;
}
class c4{
private List<C1> nid;
private List<C2> uid;
private List<C3> field_image;
}
Since you receive array from C4, you parse it like this:
public void onResponse(JSONArray response){
String value = response.toString();
GsonBuilder gb = new GsonBuilder();
Type arrayType = new TypeToken<List<C4>>() {}.getType();
List<C4> data = gb.create().fromJson(value, arrayType);
}
So in just 3 lines of code, you have your entire json serialized to java objects that you can use in your code.
Try
public void onResponse(JSONArray response) {
try {
if (response != null) {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = resultsArray.getAsJsonObject(i);
//get nid array
JSONArray nidJSONArray = jsonObject.getJSONArray("nid");
//get uid array
JSONArray uidJSONArray = jsonObject.getJSONArray("uid");
//get field_image array
JSONArray fieldImageJSONArray = jsonObject.getJSONArray("field_image");
//parse nid array
if (nidJSONArray != null) {
for (int i = 0; i < nidJSONArray.length(); i++) {
JSONObject jsonObject = nidJSONArray.getAsJsonObject(i);
String value = jsonObject.getString("value");
}
}
//parse uid array
if (uidJSONArray != null) {
for (int i = 0; i < uidJSONArray.length(); i++) {
JSONObject jsonObject = uidJSONArray.getAsJsonObject(i);
String targetId = jsonObject.getString("target_id");
String url = jsonObject.getString("url");
}
}
//parse field_image array
if (fieldImageJSONArray != null) {
for (int i = 0; i < fieldImageJSONArray.length(); i++) {
JSONObject jsonObject = fieldImageJSONArray.getAsJsonObject(i);
String targetId = jsonObject.getString("target_id");
String alt = jsonObject.getString("alt");
String title = jsonObject.getString("title");
String width = jsonObject.getString("width");
String height = jsonObject.getString("height");
String url = jsonObject.getString("url");
}
}
}
}
} catch(Exception e) {
Log.e("Error", e.getMessage());
}
}

Error parsing JSON in my Android app?

I have string json like this :
{
"listResult": {
"items": [
{
"id": "629047db-66d9-4986-ba3f-c75554198138",
"thumbnail": "http://maya-wdv-01.r.worldssl.net/39aa32db-6f50-4da1-8fd5-a5b001135b98/629047db-66d9-4986-ba3f-c75554198138/8cb69c17-0fdb-454c-bfb5-a5b9001a9d59.jpg"
},
{
"id": "fa872dc8-d2b3-4815-92ef-d90e903bc3d8",
"thumbnail": "http://maya-wdv-01.r.worldssl.net/39aa32db-6f50-4da1-8fd5-a5b001135b98/fa872dc8-d2b3-4815-92ef-d90e903bc3d8/c510c24f-5bfd-4a64-8851-a5b90017a38d.jpg"
}
],
"totalItems": 34,
"pageSize": 5,
"pageNumber": 1,
"totalPages": 7,
"searchTerm": null
}
}
I Try Parsing with code :
try {
JSONObject json = new JSONObject(response);
String listResult = json.getString(Variabel.listResult);
JSONArray items_obj = json.getJSONArray(Variabel.items);
int jumlah_list_data = items_obj.length();
if (jumlah_list_data > 0) {
for (int i = 0; i < jumlah_list_data; i++) {
JSONObject obj = items_obj.getJSONObject(i);
String id = obj.getString(Variabel.id);
String thumbnail = obj.getString(Variabel.thumbnail);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
But I getting Error :
org.json.JSONException: No value for items
So how to solve it ? sorry for my English
Instead of:
JSONObject json = new JSONObject(response);
String listResult = json.getString(Variabel.listResult);
JSONArray items_obj = json.getJSONArray(Variabel.items);
you should have:
JSONObject json = new JSONObject(response);
JSONObject listResult = json.getJSONObject(Variabel.listResult);
JSONArray items_obj = listResult.getJSONArray(Variabel.items);
Accordingly to the json you posted, items is direct child of listResult, so you have to use the JSONObject with key listResult to retrieve it. Change
JSONArray items_obj = json.getJSONArray(Variabel.items);
with
JSONArray items_obj = listResult.getJSONArray(Variabel.items);

Android parsing json

Im getting problems with parsing Json.
my json response.
{
"Persons": [
{
"id": 0,
"name": "William",
"image": "http://www.images-image2312321356.jpg",
"colors": [
"White",
"Red",
"Green"
]
},
{...}
Im trying this. but it causes a compile error
public void onResponse(JSONObject responseObject) {
try {
JSONArray rs = responseObject.getJSONArray("Persons");
for (int i = 0; i < rs.length(); i++) {
try {
final JSONObject c = rs.getJSONObject(i);
String name = c.getString("name");
items.add(name);
));
}
} catch (JSONException e) {
e.printStackTrace();
}
Any idea? Im using volley
public void onResponse(JSONObject responseObject) {
JSONArray rs = responseObject.getJSONArray("Persons");
if (rs != null || rs.length() > 0) {
for (int i = 0; i < rs.length(); i++) {
JSONObject obj = rs.getJSONObject(i);
String id = obj.getString("id");
String name = obj.getString("name");
String img = obj.getString("image");
JSONArray colors = obj.getJSONArray("colors");
for (int ii = 0; ii < colors.length(); ii++) {
String color = colors.getString(ii);
colors.add(color);
}
}
}
}

Remove JSONobject from JSONarray in Android

I have Dynamic JSON String i want to remove the last JSON object from the JSONARRAY in android. here is my dynamic JSON String in android. My json string is
("{\"findAllUsersResponse\": "+arguments[0].toString()+"}");
{
"findAllUsersResponse": [
{
"id": "kicJw2whXyuGjbNo936L",
"name": "Fghhjj",
"udid": "2AA120E3-7478-4AD4-9C68-9C0920669B84"
},
{
"id": "NEF45TWNI6-Uc_r7938R",
"name": "ssss",
"udid": "1DD083C2-7F1D-4BB3-9AB9-691A5FD251CC"
},
{
"id": "xuXY7Ah2-O-jL4Zk939D",
"name": "Test",
"udid": "A892E0AB-6732-4F42-BEFA-3157315E9EE4"
},
{
"id": "w1FnBz8B9ciWUzBk939k",
"name": "Aditi",
"udid": "A892E0AB-6732-4F42-BEFA-3157315E9EE4"
}
]
}
If your String is not going to change and you only want last object to be deleted use substring and create new string.
String finduserjson= "{\"findAllUsersResponse\": "+arguments[0].toString()+"}");
String t = finduserjson.substring(finduserjson.indexOf("{"), finduserjson.lastIndexOf(",{"));
String j = "]}";
finduserjson = t+j;
Cheers
Was facing a similar problem. There are no methods in the JSONarray object to get what you want. You could make a function to remove it. Saw this solution somewhere.
public static JSONArray remove(final int index, final JSONArray from) {
final List<JSONObject> objs = getList(from);
objs.remove(index);
final JSONArray jarray = new JSONArray();
for (final JSONObject obj : objs) {
jarray.put(obj);
}
return jarray;
}
public static List<JSONObject> getList(final JSONArray jarray) {
final int len = jarray.length();
final ArrayList<JSONObject> result = new ArrayList<JSONObject>(len);
for (int i = 0; i < len; i++) {
final JSONObject obj = jarray.optJSONObject(i);
if (obj != null) {
result.add(obj);
}
}
return result;
}
Cheers!
If you are using JSON rather than GSON or JACKSON, then you cannot call .remove() method because you would not find it there.
Best thing you can do is, re-create a new JSONArray and add required JSONObjects in it.

Categories

Resources