Getting JSONobject from JSONarray

Getting JSONObject from JSONArray

JSONArray objects have a function getJSONObject(int index), you can loop through all of the JSONObjects by writing a simple for-loop:

JSONArray array;
for(int n = 0; n < array.length(); n++)
{
JSONObject object = array.getJSONObject(n);
// do some stuff....
}

Find JSON object in JSON array

Org.json library is quite easy to use.

Example code below:

import org.json.*;

JSONObject obj = new JSONObject(" yourJSONObjectHere ");

JSONArray arr = obj.getJSONArray("networkArray");
for (int i = 0; i < arr.length(); i++)
{
String networkCode = arr.getJSONObject(i).getString("networkCode");
......
}

By iterating on your JSONArray, you can check if each object is equal to your search.

You may find more examples from: Parse JSON in Java

Java get one JSONObject from a JsonArray

You can use a loop to iterate over every item in the JSONArray and find which JSONObject has the key you want.

private int getPosition(JSONArray jsonArray) throws JSONException {
for(int index = 0; index < jsonArray.length(); index++) {
JSONObject jsonObject = jsonArray.getJSONObject(index);
if(jsonObject.getString("name").equals("apple")) {
return index; //this is the index of the JSONObject you want
}
}
return -1; //it wasn't found at all
}

You could also return the JSONObject instead of the index. Just change the return type in the method signature as well:

private JSONObject getPosition(JSONArray jsonArray) throws JSONException {
for(int index = 0; index < jsonArray.length(); index++) {
JSONObject jsonObject = jsonArray.getJSONObject(index);
if(jsonObject.getString("name").equals("apple")) {
return jsonObject; //this is the index of the JSONObject you want
}
}
return null; //it wasn't found at all
}

How to get Json Object from json Array?

First Created POJO Class for Promotional Prices with getters and setters after that get JSONArray from JSONObject and access promotional prices.

JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = jsonObject.getJSONArray("data"); // Declare Model Class of array element

for(int i=0;i<jsonArray.size();i++)
{
PromotionalPrice promotionalPrice = jsonArray.get(i).getPromotionalPrices();
Log.d(TAG,promotionalPrice.price_promotion.toString());
}

Getting a JSON Object from a JSON Array isn't working

the error you are getting is because you aren't passing the String response to jsonObject so it can't find any thing in an empty object

the fix is

String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}

JSONObject jsonRes = new JSONObject(inputString); \\this is the fix
JSONArray common = jsonRes.getJSONArray("common");

Can't get JSONObject from JSONArray

To create a json object from an array, the array has to be associative so you can change your code to this to archieve that.

  while($array = mysqli_fetch_assoc($result)){
$jsonData[] = $array;
}


Related Topics



Leave a reply



Submit