kabuto178 kabuto178 - 6 months ago 34
Java Question

JSONObject vs JARRAY getting array length

I have a JSONObject that I pass to a method to get processed into

ArrayLists
.

{
"set0" :
{
"title" : "Do you win?",
"answer" : "1",
"imgUrl" : "imag",
"id" : "1"
},
"set1" :
{
"title" : "Did you loose?",
"answer" : "1",
"imgUrl" : "imag",
"id" : "2"
}
}


The method is structured like this:

questions(JSONObject result){

// initialization
for(int i=0;i < result.length();i++){
question_list.add(result.getJSONObject("set"+i).getString("title"));
answer_list.add(result.getJSONObject("set"+i).getString("answer"));
img_list.add(result.getJSONObject("set"+i).getString("imgUrl"));
question_batch.add(result.getJSONObject("set"+i).getInt("id"));
}
// rest of code
}


I normally see the jsonarray being used for the loop condition and not the jsonobject itself, when my jsonobject gets bigger but in the same structure as posted above will
result.length()
start to yield a wrong result and is this an incorrect implementation for someone who will want to iterate through their jsonobject?

Answer

I'm not sure if your implementation is "incorrect", but this is how I generally iterate through JSON.

int i = 0;
boolean continue = true;
while (continue){
    if (result.has("set" + i){

    JSONObject set = result.get("set" + i.toString());

    if (set.has("title"){
        question_list.add(set.getString("title");
    }
    if (set.has("answer"){
        answer_list.add(set.getString("answer");
    }
    if (set.has("imgUrl"){
        image_list.add(set.getString("imgUrl");
    }
    if (set.has("id"){
        question_batch.add(set.getInt("id");
    }

    i++;

    }else{
        continue = false;
    }
}

This is a little more efficient because you don't have to create a new JSON object everytime you want to pull data out. Also I would make a new class to handle the JSON objects, and make the array list of that type, so you only have to add one object for each iteration. This way, you can be sure that your questions/answers/imageURLs/id's are all kept together. Like this:

    JSONObject set = result.get("set" + i.toString());

    QuestionObject newQuestion = new QuestionObject();

    if (set.has("title"){
        newQuestion.setTitle(result.getString("title");
    }
    if (set.has("answer"){
        newQuestion.setAnswer(result.getString("answer");
    }
    if (set.has("imgUrl"){
        newQuestion.setImageURL(result.getString("imgUrl");
    }
    if (set.has("id"){
        newQuestion.setID(result.getInt("id");
    }

    questionList.add(newQuestion);

Also, in case you didn't notice, you can directly parse integers using json.getInt for your "id" field instead of string. Hope this helps.

Comments