This is my first time working with json and I'm having a hard time trying to filter an array I'm trying to get all values (tienda) where id_estado=1.
Any clue how to approach this?
JA1= [{"id_estado":"1","tienda":"Aurrera"},{"id_estado":"1","tienda":"Walt-Mart"},{"id_estado":"1","tienda":"Chedraui"},{"id_estado":"1","tienda":"Soriana"},{"id_estado":"1","tienda":"Comercial MX"},{"id_estado":"1","tienda":"City Market"},{"id_estado":"2","tienda":"Walt-Mart"},{"id_estado":"2","tienda":"Chedraui"},{"id_estado":"2","tienda":"Aurrera"},{"id_estado":"2","tienda":"Superama"}]
JSONArray JA1=new JSONArray(result1);
JSONObject json1= null;
name = new String[JA1.length()];
for (int i = 0; i < JA1.length(); i++) {
Log.d("LOG", "resultado name sin arreglo11 " + JA1);
//name[i] = json1.getString("tienda");
//name[i]=json1.getString("estado");
}
for(int i=0;i<name.length;i++)
{
list2.add(name[i]);
Log.d("LOG", "resultado name2 " + name[i]);
}
Thanks in advance
Here's how I'd do it:
try {
List<String> filtered = new ArrayList<>();
JSONArray ary = new JSONArray(/* your json here */);
for (int i = 0; i < ary.length(); ++i) {
JSONObject obj = ary.getJSONObject(i);
String id = obj.getString("id_estado");
if (id.equals("1")) {
filtered.add(obj.getString("tienda"));
}
}
} catch (JSONException e) {
// handle exception
}
An explanation of this code:
ArrayList to hold the filtered values.JSONArray from your json text.JSONObject each time.id_estado property and check if it is equal to "1".tienda property to the list of filtered values.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With