سؤال

I try to learn Loop through a JSON object in Java for loop this case.But My json loop first array(ident AFL274) and stop not loop next array(CQH8971)(in json data have 2 arrays)I call this function by button.

this for call for json

public String getInfo(String url) {  
    try {
        String result  = HttpGet(url);
        JSONObject json = new JSONObject(result);
        JSONObject val = json.getJSONObject("SearchResult");
        JSONArray data = val.getJSONArray("aircraft");

        for(int i=0;i<data.length();i++)
        {
            JSONObject data1 = data.getJSONObject(i);
            String ans = data1.getString("ident");
        }

    } catch (JSONException e) {
        e.printStackTrace();
    } 

    return ans;
}

and this JSON:

{
    "SearchResult": {
        "next_offset": -1,
        "aircraft": [
            { 
                "ident": "AFL274", 
                "type": "B77W" 
            },
            { 
                "ident": "CQH8971", 
                "type": "A320"
            }
        ]
    }
}
هل كانت مفيدة؟

المحلول

Try this,

public String[] getInfo(String url) {  
    try {
        String result  = HttpGet(url);
        JSONObject json = new JSONObject(result);
        JSONObject val = json.getJSONObject("SearchResult");
        JSONArray data = val.getJSONArray("aircraft");
        int arrayLength = data.length();
        String[] strAryAns = new String[arrayLength]; 

        for(int i=0;i<arrayLength;i++)
        {
            JSONObject data1 = data.getJSONObject(i);
            strAryAns[i] = data1.getString("ident");
        }

    } catch (JSONException e) {
        e.printStackTrace();
    } 

    return strAryAns;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top