Android - 从json获取数据

时间:2014-11-07 16:45:58

标签: android json

我有一个api调用,返回这个json对象:

{
    "elenco": [
        "folder 1",
        "folder 2",
        "folder 3"
    ],
    "codice": "123456789"
}

这是我得到结果的代码:

protected void onPostExecute(JSONObject result) {

        // Close progress dialog
        Dialog.dismiss();

        JSONObject jobj = null;
        String codice_utente = null;
        JSONArray elenco_cartelle = null;

        try {

            jobj = new JSONObject(String.valueOf(result));

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

        //Provo a recuperare i campi json
        try {

            codice_utente = jobj.getString("codice");
            elenco_cartelle = jobj.getJSONArray("elenco");

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

        //This should fetch the elenco array
        for (int i = 0; i < elenco_cartelle.length(); i++) {  

            JSONObject childJSONObject = null;

            try {

                childJSONObject = elenco_cartelle.getJSONObject(i);

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

           //Can't use getString here...

        }



    }

如何获取elenco部分?我没有使用密钥,那么如何在ArrayList中添加每一行? 我尝试使用for,但我不知道如何获取行

1 个答案:

答案 0 :(得分:0)

使用JSONArray.getString() http://developer.android.com/reference/org/json/JSONArray.html#getString(int)

for (int i = 0; i < elenco_cartelle.length(); i++) {  

            String content = null;

            try {

                content = elenco_cartelle.getString(i);

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

       //Can't use getString here...

    }

现在,您的内容位于content