Jaison Brooks
Jaison Brooks

Reputation: 5826

Use values (integers) returned in JSONArray

Im having issues with being able to get the indivisual responses from this JSON Array. Im trying to write some code that will allow me to use the vaules indivisually, as well as how to combine them if i needed too. These responses are always integers.

Java

JSONObject jsonObj = new JSONObject(jsonStr);
data_array = jsonObj.getJSONArray("data");

  for (int i = 0; i < data_array.length(); i++) {

      JSONObject prod = data_array.getJSONObject(i);
          Log.d("Logging Response", prod);
}

Json

[5652,8388,8388,7537,8843,2039,8235,0,12220]

I'd like to figure out how i can add them together and return the calculated result, as well as how to use them individually. such as (prod + prod + prod) etc...

Upvotes: 0

Views: 1895

Answers (4)

Pankaj Kumar
Pankaj Kumar

Reputation: 82958

JSONArray data = jsonObj.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
    Integer prod = (Integer) data.get(i);
    System.out.println("Prod " + prod);
    // loop and add it to array or arraylist
}

Upvotes: 1

Biraj Zalavadia
Biraj Zalavadia

Reputation: 28484

 JSONArray jsonObj = new JSONArray(jsonStr);
            
            for (int i = 0; i < jsonObj.length(); i++) {
                System.out.println(jsonObj.getString(i));
            }

Upvotes: 1

Dinithe Pieris
Dinithe Pieris

Reputation: 1992

To put that json array data in to a new json object, try this:

JSONObject jsonObj = new JSONObject(jsonStr);
data_array = jsonObj.getJSONArray("data");
JSONObject prod;

for (int i = 0; i < data_array.length(); i++) {
  prod.put(i,data_array.getJSONObject(i));
      Log.d("Logging Response", prod);
}

Upvotes: 1

Nambi
Nambi

Reputation: 12042

You have the jsonarray as the response

ArrayList<Integer> jsonvalue=new ArrayList<Integer>();
    for (int i = 0; i < data_array.length(); i++) {

      int i=     data_array.getInt(i);
jsonValue.add(i)
        }

Upvotes: 1

Related Questions