How to remove JSONArray element using Java - java

My JsonArray is
[{
"Id": null,
"Name": "One New task",
"StartDate": "2010-02-03T05:30:00",
"EndDate": "2010-02-04T05:30:00",
"Duration": 1,
"DurationUnit": "d",
"PercentDone": 0,
"ManuallyScheduled": false,
"Priority": 1,
"parentId": 8,
"index": 0,
"depth": 3,
"checked": null },{
"Id": null,
"Name": "New task",
"StartDate": "2010-02-04T05:30:00",
"EndDate": "2010-02-04T05:30:00",
"Duration": 0,
"DurationUnit": "d",
"PercentDone": 0,
"ManuallyScheduled": false,
"Priority": 1,
"parentId": 8,
"index": 1,
"depth": 3,
"checked": null }]
Now from this JsonArray I want to remove Id, ManuallyScheduled, checked,
I tried using jsonArray.remove(1) and also jsonArray.discard("Id") in JAVA.
but nothing happens. what am I doing wrong to remove array items?
I am using JAVA as my technology.

What you have there is an array of objects. Therefore you'll have to loop through the array and remove the necessary data from each object, e.g.
for (int i = 0, len = jsonArr.length(); i < len; i++) {
JSONObject obj = jsonArr.getJSONObject(i);
// Do your removals
obj.remove("id");
// etc.
}
I've assumed you're using org.json.JSONObject and org.json.JSONArray here, but the principal remains the same whatever JSON processing library you're using.
If you wanted to convert something like [{"id":215},{"id":216}] to [215,216] you could so something like:
JSONArray intArr = new JSONArray();
for (int i = 0, len = objArr.length(); i < len; i++) {
intArr.put(objArr.getJSONObject(i).getInt("id"));
}

This is useful sometimes in android when you want to use the json structure directly.
Notice that I only use this when I'm handling JSONObject inside the array.
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;
}

The following method will find the object in an array with the matching id, then return the filtered array.
public JSONArray removeObject(JSONArray array, String id) throws JSONException {
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
if (obj.getString("ID").equals(id)) {
array.remove(i);
// Toast.makeText(this, "ENCONTRADO", Toast.LENGTH_SHORT).show();
}
}
return array;
}

Related

Get specific index of JSON Nested objects in java Android

How I can get only the "name" string of every object under "fields" Array, of main Array index at 0 & then next index using loop or with something super idea
[
{
"name": "Bank1",
"fields": [
{
"name": "Email",
"slug": "email",
"type": "input"
},
{
"name": "City",
"slug": "city",
"type": "input"
},
{
"name": "Screenshot",
"slug": "screenshot",
"type": "file"
},
{
"name": "Full Name",
"slug": "full-name",
"type": "input"
}
],
"status": "Active"
},
{
"name": "Bank2",
"fields": [
{
"name": "Email",
"slug": "email",
"type": "input"
},
{
"name": "City",
"slug": "city",
"type": "input"
},
{
"name": "Screenshot",
"slug": "screenshot",
"type": "file"
},
{
"name": "Submitted Date",
"slug": "submitted-date",
"type": "calendar"
}
],
"status": "Active"
}
]
Output I want:
Email
City
Screenshot
Full Name
Means in the output, I have got index 0, first object array data...
What I have done yet
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String p_name = jsonObject.getString("name");
ArrayList<String> arr = new ArrayList<>();
JSONArray ja = jsonObject.getJSONArray("fields");
int len = ja.length();
for (int j = 0; j < len; j++) {
JSONObject json = ja.getJSONObject(j);
arr.add(json.getString("name"));
}
}}catch block...
this gives me all indexes name data i want only specific index data
My Current Output:
Email
City
Screenshot
Full Name
Email
City
Screenshot
Submitted Date
If you want to get specific index data then you should pass if condition in for loop.
EX: to get output of index 0 like,
Email
City
Screenshot
Full Name
Your code would be like below.
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
if(i==0){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String p_name = jsonObject.getString("name");
ArrayList<String> arr = new ArrayList<>();
JSONArray ja = jsonObject.getJSONArray("fields");
int len = ja.length();
for (int j = 0; j < len; j++) {
JSONObject json = ja.getJSONObject(j);
arr.add(json.getString("name"));
}
}
}}catch block...
int i=gotIndex;//here you can give your exact index that you want
JSONObject jsonObject = jsonArray.getJSONObject(i);
String p_name = jsonObject.getString("name");
ArrayList<String> arr = new ArrayList<>();
JSONArray ja = jsonObject.getJSONArray("fields");
int len = ja.length();
for (int j = 0; j < len; j++) {
JSONObject json = ja.getJSONObject(j);
arr.add(json.getString("name"));
}
here you used the loop you can use the json object out side the loop with using the index number i (jsonObject = jsonArray.getJSONObject(i))

How can i go through this json in java?

I am working on an Android project, in which I am using Volley to consume an Api. The query is being done correctly and the next JSON returns to me. I am trying to access the elements of this jsonArray in java
[
{
"Estado": 1,
"_id": "5dfd27fb971f730f31cc12d5",
"empresas": "5dfbeec1f87e0e3030b38143",
"Codigo": "1001AZXL001",
"Codigo_Barras": "7702345654127",
"Descripcion": "JEAN talla XL ",
"Detalles": [
{
"_id": "5dfd27fb971f730f31cc12d7",
"bodegas": "5dfd2383971f730f31cc12cf",
"Cantidad": 6,
"Precio": 150000,
"Unidad_Medida": "UND"
},
{
"_id": "5dfd27fb971f730f31cc12d6",
"bodegas": "5dfd23b7971f730f31cc12d0",
"Cantidad": 15,
"Precio": 150000,
"Unidad_Medida": "UND"
}
],
"Talla": "XL",
"Color": "AZ",
"Minimo": 5000,
"Maximo": 30000,
"Fecha_Creacion": "2019-12-20T19:58:51.720Z"
}
]
For that I am using the following code
public void onResponse(JSONArray jsonArray) {
for(int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
descripcionProducto = jsonObject.getString("Descripcion");
tallaProducto = jsonObject.getString("Talla");
txtDescripcion.setText(descripcionProducto);
txtUnidades.setText(tallaProducto);
}
catch(JSONException e) {
}
}
}
But I cannot access the elements that are inside the "Detalles" object
Use the following :
public void onResponse(JSONArray jsonArray) {
for(int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
descripcionProducto = jsonObject.getString("Descripcion");
tallaProducto = jsonObject.getString("Talla");
txtDescripcion.setText(descripcionProducto);
txtUnidades.setText(tallaProducto);
JSONArray array = jsonObject.getJSONArray("Detalles")
for(int j = 0; j < array.length() ; ++j){
try{
JSONObject jsonObject2 = array.getJSONObject(j);
//ACCESS THE PARAMETERS OF detalles HERE FOR EX :
String bodegas = jsonObject2.getString("bodegas");
}catch(JSONException e) {}
}
}
catch(JSONException e) {
}
}
}
This is another Jsonarray, if you want to get the data inside, you Need to get the Jsonarray and read the data from there.
JSONArray array = jsonObject.getJSONArray("Detalles")
If you want the Data inside this Array you can Access them as you already did

Put JSONObjet into JSONArray

I have a problem putting JSONObject into JSONArray.
Here is my code:
String strObject = "{\"Code\":\"a\", \"Name\": \"b\"}";
JSONObject anExistedObject = new JSONObject(strObject);
JSONArray myArray = new JSONArray();
for(int count = 0; count < 2; count++){
JSONObject myObject = new JSONObject;
myObject = anExistedObject;
myObject.put("Count", count);
myArray.put(myObject);
}
System.out.println(myArray.toString());
Result:
[
{
"Code": "a",
"Name": "b",
"Count": 1
},
{
"Code": "a",
"Name": "b",
"Count": 1
}
]
What I expected:
[
{
"Code": "a",
"Name": "b",
"Count": 0
},
{
"Code": "a",
"Name": "b",
"Count": 1
}
]
I've read this post but still don't know how to fix mine.
Did I missed something?
You each time modify same object because of line: myObject = anExistedObj;
You need make copy of that object instead.
Correct code:
JSONObject anExistedObj = new JSONObject();
myObject.put("Code", "a");
myObject.put("Name", "a");
JSONArray myArray = new JSONArray();
String[] keys = JSONObject.getNames(anExistedObj);
for(int count = 0; count < 2; count++){
JSONObject myObject = new JSONObject(anExistedObj, keys);
//anExistedObj = {"Code":"a", "Name": "b"}
myObject.put("Count", count);
myArray.put(myObject);
}
System.out.println(myArray.toString());
Checkout documentation of copy constructor JSONObject
You are updating and reusing anExistedObject everytime
String strObject = "{\"Code\":\"a\", \"Name\": \"b\"}";
JSONArray myArray = new JSONArray();
for(int count = 0; count < 2; count++){
JSONObject myObject = new JSONObject(strObject);
myObject.put("Count", count);
myArray.put(myObject);
}
System.out.println(myArray.toString());
This happens because the line myObject.put("Count", count); always modifies the same object since the variable is only a reference to the object itself. Meaning that myObject and anExistedObject point to the same object.
You should create a copy with:
JSONObject copy = new JSONObject(original, JSONObject.getNames(original));
Instead of using:
JSONObject myObject = new JSONObject;
myObject = anExistedObj;

JSON get Array without object

I'm trying to parse this JSON,
{
"listname": "red",
"lists": [
{
"id": "01",
"name": "paw",
"list": [
{
"id": "A",
"name": "pawa",
"bar": "foo"
},
{
"id": "B",
"name": "pawb",
"bar": "foo"
}
]
},
{
"id": "02",
"name": "pew",
"list": [
{
"id": "A",
"name": "pewa",
"bar": "foo"
},
{
"id": "B",
"name": "pewb",
"bar": "foo"
}
]
},
{
"id": "03",
"name": "piw",
"list": [
{
"id": "A",
"name": "piwa",
"bar": "foo"
},
{
"id": "B",
"name": "piwb",
"bar": "foo"
}
]
}
]
}
I put it on Asset Folder and I read it and it converts it to me to String since here all good, the problem is when I'm trying to get the name from each item of lists and trying to get all the names from the list I've tried it doing this :
JSONObject obj = new JSONObject(str);
JSONArray jsonMainArr = obj.getJSONArray("lists"); //first get the lists
for (int i = 0; i < jsonMainArr.length(); i++) {
JSONObject childJSONObject = jsonMainArr.getJSONObject(i);
String name = childJSONObject.getString("name");
Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
}
JSONObject obj = new JSONObject(str);
JSONArray jsonMainArr = obj.getJSONArray("list"); //get the list
for (int i = 0; i < jsonMainArr.length(); i++) {
JSONObject childJSONObject = jsonMainArr.getJSONObject(i);
String name = childJSONObject.getString("name");
Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
}
But it doesn't show anything... what I'm missing?
EDIT
This is how I read the JSON
public static String loadJSONFromAsset(Context ctx, String str) {
String json = null;
try {
InputStream is = ctx.getAssets().open(str);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
Since your "list" is nested in the childJSONObject (from "lists") , nest your for loops to retrieve the this set of values (the JSONobject)
JSONObject obj = new JSONObject(str);
//first get the top-level "lists"
JSONArray jsonMainArr = obj.getJSONArray("lists");
for (int i = 0; i < jsonMainArr.length(); i++) {
JSONObject childJSONObject = jsonMainArr.getJSONObject(i);
String name = childJSONObject.getString("name");
Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
//get the inner "list" from childJSONObject
JSONArray childJSONArray = childJSONObject.getJSONArray("list");
for (int j = 0; j < childJSONArray.length(); j++) {
JSONObject childJSONObjectB = childJSONArray.getJSONObject(j);
String name = childJSONObjectB.getString("name");
Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
}
}

How to get JSONArray exists in another JSONArray?

I have a JSONArray contained in another JSONArray in a JSON Object like the following:
{
"protocol": "test",
"query": [
{
"locked": false,
"ids": [
{
"id": 1,
"locked": false
},
{
"id": 1,
"locked": false
}
]
},
{
"locked": false,
"ids": [
{
"id": 1,
"locked": false
},
{
"id": 1,
"locked": false
}
]
}
],
}
here i want to get the ids arrays, i can get the query arrays like that:
private JSONArray getDB_Query(String json) throws JSONException{
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(json);
} catch (JSONException e) {
Login.errorMessage.setText(sys_err);
}
JSONArray query = jsonObj.getJSONArray("query");
return query;
}
Now if I want to get the ids, is that true :
jsonObj = new JSONObject(query.toString()); // query is the JSONArray I retrieved from the above method
for(int i= 0; i < query.length(); i ++){
JSONArray ids_query = jsonObj.getJSONArray("ids");
}
update your last for loop like:
for(int i= 0; i < query.length(); i ++){
JSONArray ids_query = query.getJSONObject(i).getJSONArray("ids");
}

Categories

Resources