14

I am trying to get a list of available numbers from the following json object, using the class from org.json

    {
        "response":true,
        "state":1,
        "data":
        {
            "CALLERID":"81101099",
            "numbers":
                [
                       "21344111","21772917",
                       "28511113","29274472",
                       "29843999","29845591",
                       "30870001","30870089",
                       "30870090","30870091"
                ]
        }
    }

My first steps were, after receiving the json object from the web service:

jsonObj = new JSONObject(response);
jsonData = jsonObj.optJSONObject("data");

Now, how do I save the string array of numbers?

Laksh
  • 6,717
  • 6
  • 33
  • 34
CodePrimate
  • 6,646
  • 13
  • 48
  • 86

4 Answers4

43

use:

jsonObj = new JSONObject(response);
jsonData = jsonObj.optJSONObject("data");
JSONArray arrJson = jsonData.getJSONArray("numbers");
String[] arr = new String[arrJson.length()];
for(int i = 0; i < arrJson.length(); i++)
    arr[i] = arrJson.getString(i);
Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
jeet
  • 29,001
  • 6
  • 52
  • 53
  • 1
    Except for the fact that there's no method in JSONArray named getLength(did you mean length() ? ) this was great - thanks :) – CodePrimate Feb 21 '12 at 08:44
  • If you're specifying strings, it looks like you have to cast the value of arrJson.get(i) to String. – Laurent Mar 17 '15 at 06:23
  • It shows null pointer exception. `getString(i)` retrieves the value in the form of string. But in OP's case the JSONArray's elements do not have value. – NullByte08 May 02 '20 at 21:47
3

you need to use JSONArray to pull data in an array

JSONObject jObj= new JSONObject(your_json_response);
JSONArray array = jObj.getJSONArray("data");
waqaslam
  • 67,549
  • 16
  • 165
  • 178
1

My code is for getting "data":

public void jsonParserArray(String json) {

        String [] resultsNumbers = new String[100];

        try {
            JSONObject jsonObjectGetData = new JSONObject(json);
            JSONObject jsonObjectGetNumbers = jsonObjectGetData.optJSONObject("results");
            JSONArray jsonArray = jsonObjectGetNumbers.getJSONArray("numbers");
            for (int i = 0; i < jsonArray.length(); i++) {
                resultsNumbers[i] = jsonArray.getString(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            Log.e(LOG_TAG, e.toString());
        }
    }
QuartZ
  • 154
  • 3
  • 12
0

Assuming that you are trying to get it in a javascript block, Try something like this

var arrNumber = jsonData.numbers;

ahsan_cse2004
  • 182
  • 4
  • 16