-1

I have JSON :

{"elements":[{"id":5,"name":"Mathematics","shortName":"math","links":{"courses":[15,30,46,47]}}]}

My code :

 List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

            // Check your log cat for JSON reponse
            //Log.d("All Products: ", json.toString());

            try {
                products = json.getJSONArray("elements");

                for (int i = 0; i < products.length(); i++) {
                    JSONObject c = products.getJSONObject(i);

                    // Storing each json item in variable
                    int ids = c.getInt(TAG_PID);
                    String id = String.valueOf(ids);

                    if (id.compareTo(id_kh) == 0) {
                        object = c.getJSONObject("links");
                        JSONArray courses = object.getJSONArray("courses");///???????????
                        //result = courses.split("[,]");
                        Toast.makeText(getBaseContext(),"abc",Toast.LENGTH_LONG).show();
                        break;
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

I dont know to get array number after "courses".

Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358
imTony
  • 42
  • 2
  • 8

3 Answers3

0

courses is a JSONArray, so you can do like that:

JSONArray coursesArray = linksObject.getJSONArray("courses");

UPDATE:

To get values from coursesArray :

int value = coursesArray.optInt(position);
Rami
  • 7,879
  • 12
  • 36
  • 66
0

I would use HashMaps. Here you have an example (creating Hashmap from a JSON String ) how to get it from a JSON String.

Particularly for the "courses", once you have been parsed until there, I would use a HashMap<String,List<Integer>>

Community
  • 1
  • 1
juanmg
  • 1
  • 1
0

Almost there. Once you get your

JSONArray courses = object.getJSONArray("courses");

simply iterate over its values:

// you wanted these numbers in an array
// so let's create one, with size being number of elements in 
// JSONArray courses
int[] courseIds = new int[courses.length()];

for (int j=0; j<courses.length(); j++) {
    // assign current number to the appropriate element in your array of ints
    coursesId[j] = courses.getInt(j);
    Log.d("TAG", "number: " + number);
}

The above will save these numbers in an array and print them too:

number: 15

number: 30

number: 46

number: 47

Just keep in mind that "courses" key might not exist, the array might be empty etc.

Community
  • 1
  • 1
Melquiades
  • 8,496
  • 1
  • 31
  • 46