Remove JSONobject from JSONarray in Android - 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.

Related

Remove a Jsonobject based on some key-value from JsonArray 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

Getting JSON Array values Within a JSOn Object and Use In Class Object

I am trying to populate a class object with JSON data, and I keep getting this error
org.json.JSONException: No value for machinereports
Here is the sample json file, I am trying to use
{
"id" : 1,
"reports": [
{
"id": "1",
"title": "For Reorder",
"subtitle": "Report Name",
"date": "Monday, Aug 08, 2016",
"machinereports": [
{
"name": "Reorder List",
"count": "9"
},
{
"name": "Reorder List Critical",
"count": "9"
}
]
}
]
}
Here is the code I am trying to retrieve and populate my class object with
public class Report {
public String id;
public String title;
public String subtitle;
public String date;
public ArrayList<String> machinereports = new ArrayList<>();
public static ArrayList<Report> getReportsFromFile(String filename, Context context) {
final ArrayList<Report> reportList = new ArrayList<>();
try {
// Load Data
String jsonStr = loadJsonFromAsset("reports.json", context);
JSONObject jsonOne = new JSONObject(jsonStr);
JSONArray reports = jsonOne.getJSONArray("reports");
// Get Report objects from data
for(int i = 0; i < reports.length(); i++) {
Report report = new Report();
report.id = reports.getJSONObject(i).getString("id");
report.title = reports.getJSONObject(i).getString("title");
report.subtitle = reports.getJSONObject(i).getString("subtitle");
report.date = reports.getJSONObject(i).getString("date");
// Get inner array listOrReports
JSONArray rList = jsonOne.getJSONArray("machinereports");
for(int j = 0; j < rList.length(); j++) {
JSONObject jsonTwo = rList.getJSONObject(j);
report.machinereports.add(jsonTwo.getString("reportName"));
/* report.machinereports.add(jsonTwo.getString("count"));*/
}
reportList.add(report);
}
} catch (JSONException e) {
e.printStackTrace();
}
return reportList;
}
I can't seem to figure out, where I am having the problem, when I step through, when it gets to second JSONArray object it goes to the catch exception.
Your JSON does not have a field named reportName.
report.machinereports.add(jsonTwo.getString("reportName"));
change it to
report.machinereports.add(jsonTwo.getString("name"));
Also with the answer from #comeback4you you have the wrong call to the JsonArray.
JSONArray rList = jsonOne.getJSONArray("machinereports");
Should be
JSONArray rList = reports.getJSONObject(i).getJSONArray("machinereports");
JSONArray rList = jsonOne.getJSONArray("machinereports");
change to
JSONArray rList = reports.getJSONObject(i).getJSONArray("machinereports");
and inside for loop change below
report.machinereports.add(jsonTwo.getString("name"));

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);

Get Specific Value from JSONArray

i got an jsonarray:
[
{
"ean": "8020079127",
"nr": "100",
"name": "Name1"
},
{
"ean": "8026180222",
"nr": "4",
"name": "Name2"
},
{
"ean": "6577426092",
"nr": "1",
"name": "Name3"
}
]
I need the value from "nr" depending on the "ean" means:
I got the ean 8026180222 (as string) and need the value from the "nr" (here "4"). how I can get it?
its possible without iterate over the whole array?
thank you
Try this:
// Use a map to store ean,nr (as key/value)
HashMap<String, String> jsonMap = new HashMap<String, String>();
// Load the data from json
JSONArray jsonArray= new JSONArray(yourJsonString);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
String ean = jsonObj.getString("ean");
String nr = jsonObj.getString("nr");
String name = jsonObj.getString("name");
jsonMap.put(ean, nr); // here you put ean as key and nr as value
}
To retrieve an nr value of a specific ean just call: jsonMap.get(yourEAN);
Example: String nr = jsonMap.get("8026180222");
List<NameValuePair> params = new ArrayList<NameValuePair>();
JsonObject json = jsonParser.makeHttpRequest(url, "GET", params);
Log.d("Tag", json.toString());
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
JSONArray jsnObj;
try {
jsnObj = json
.getJSONArray(TAG_ARRAY);
JSONObject obj = jsnObj
.getJSONObject(1);
String nr = obj.getString(TAG_NR);
}
Catch(Exception ex){}
}
}
If you want array you can use loops in json array.....................Hope it will help
Just define
private static final String TAG_SUCCESS = "success";
private static final String TAG_NR = "nr";
private static final String TAG_ARRAY = "array_name";

Android parse json tree

I have tree JSON-structured data.
Something like
{
"result": [
{
"id": 1,
"name": "test1"
},
{
"id": 2,
"name": "test12",
"children": [
{
"id": 3,
"name": "test123",
"children": [
{
"id": 4,
"name": "test123"
}
]
}
]
}
]
}
model:
class DataEntity {
int id;
String name;
List<DataEntity> childDataEntity;
}
Parsing via org.json
List<DataEntity> categories = new ArrayList<DataEntity>();
private List<DataEntity> recursivellyParse(DataEntity entity, JSONObject object) throws JSONException {
entity.setId(object.getInt("id"));
entity.setName(object.getString("name"));
if (object.has("children")) {
JSONArray children = object.getJSONArray("children");
for (int i = 0; i < children.length(); i++) {
entity.setChildDataEntity(recursivellyParse(new DataEntity(), children.getJSONObject(i)));
categories.add(entity);
}
}
return categories;
}
call
JSONObject jsonObject = new JSONObject(JSON);
JSONArray jsonArray = jsonObject.getJSONArray("result");
for (int i = 0; i < jsonArray.length(); i++) {
recursivellyParse(new DataEntity(), jsonArray.getJSONObject(i));
}
But this way is wrong. After execution of the method List filled out same data.
How do I parse it right?
UPD: update JSON.
Here is Full Demo How to Parse json data as you want.
String JSON = "your json string";
ArrayList<DataEntity> finalResult = new ArrayList<>();
try {
JSONObject main = new JSONObject(JSON);
JSONArray result = main.getJSONArray("result");
for(int i=0;i<result.length();i++){
DataEntity dataEntity = parseObject(result.getJSONObject(i));
finalResult.add(dataEntity);
}
Log.d("DONE","Done Success");
} catch (JSONException e) {
e.printStackTrace();
}
Create One recursive function to parse object.
public DataEntity parseObject(JSONObject dataEntityObject) throws JSONException {
DataEntity dataEntity = new DataEntity();
dataEntity.id = dataEntityObject.getString("id");
dataEntity.name = dataEntityObject.getString("name");
if(dataEntityObject.has("children")){
JSONArray array = dataEntityObject.getJSONArray("children");
for(int i=0;i<array.length();i++){
JSONObject jsonObject = array.getJSONObject(i);
DataEntity temp = parseObject(jsonObject);
dataEntity.children.add(temp);
}
}
return dataEntity;
}
Model Class
public class DataEntity implements Serializable {
public String id = "";
public String name = "";
ArrayList<DataEntity> children = new ArrayList<>();}
In FinalResult Arraylist you will get all your parse data.
Ignoring that the JSON you show is invalid (i'm going to assume that's a copy/paste problem or typo), the issue is that you've declared your categories List as a member of whatever object that is.
It's continually getting added to on every call to recursivellyParse() and that data remains in the list. Each subsequent call from your loop is seeing whatever previous calls put in it.
A simple solution to this as your code is written would be to simply add a second version that clears the list:
private List<DataEntity> beginRecursivellyParse(DataEntity entity,
JSONObject object) throws JSONException {
categories.clear();
return recursivellyParse(entity, object);
}
Then call that from your loop.

Categories

Resources