我不能通过JSON数组循环下一个数组

时间:2014-03-02 04:32:46

标签: java android json getjson

我尝试学习Loop through a JSON object in Java for循环这种情况。但是我的json循环第一个数组(ident AFL274)并且停止不循环下一个数组(CQH8971)(在json数据中有2个数组)我通过按钮调用这个函数

这是为了调用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;
}

和这个JSON:

{
    "SearchResult": {
        "next_offset": -1,
        "aircraft": [
            { 
                "ident": "AFL274", 
                "type": "B77W" 
            },
            { 
                "ident": "CQH8971", 
                "type": "A320"
            }
        ]
    }
}

1 个答案:

答案 0 :(得分:0)

试试这个,

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;
}