Salam El-Banna
Salam El-Banna

Reputation: 3870

JSONObject getString(String.valueof(variable integer)) not working

I have searched a lot for an answer or an explanation why "JSONObject.getString()" is not working. First this is the response from php server

{"3":["S1","2013","Final"],"2":["S0","2010","Mid"],"1":["S6","2015","Final"]}

This is my code:

        CCNERequest.add(new BasicNameValuePair("Semester", "S"));
        CcneJsonString = CCNEexams.getJSONFromUrl(CCNEUrl, CCNERequest);
        if (CcneJsonString != null) {
            try {
                JSONObject jObj = new JSONObject(CcneJsonString);
             for (int i = 0; i < jObj.length(); i++) {

                    JSONArray jsonArray = new JSONArray(
                            jObj.getString(values[i]));
              }

This code is working fine with me while values[] is an array implemented like this:

public String[] values = { "1", "2", "3", "4", "5", "6", "7", "8", "9",
        "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20",
        "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31",
        "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42",
        "43", "44", "45", "46", "47", "48", "49", "50" };

Now in future I might have more than 1000 JSONObjects, I don't want to implement the array values[] since I want to wright nice code and efficient, so I tried to replace the array values[i] by the exact number of JSONObjects like this:

CCNERequest.add(new BasicNameValuePair("Semester", "S"));
        CcneJsonString = CCNEexams.getJSONFromUrl(CCNEUrl, CCNERequest);
        if (CcneJsonString != null) {
            try {
                JSONObject jObj = new JSONObject(CcneJsonString);
             for (int i = 0; i < jObj.length(); i++) {

                    JSONArray jsonArray = new JSONArray(
                            jObj.getString(String.valueOf(i));
              }

In that way I don't have to implement values[] previously in the code but unfortunately this is not working, it is throwing an exception On

JSONArray jsonArray = new JSONArray(
                            jObj.getString(String.valueOf(i));

So my question is, Why it is making an exception error while giving a converted variable to string in JSONObject.getString() and is their any way to get rid of the array of strings values[] and use another method that gives me the same results without implementing something static??

Upvotes: 1

Views: 2282

Answers (1)

mattm
mattm

Reputation: 5949

In the first loop iteration, i is 0, but there is no key 0 in the JSONObject. This results in a JSONException.

You should start the loop from 1.

Upvotes: 1

Related Questions