如何在Android中从PHP管理和读取JSON数组

问题描述:

我有很多以这种方式格式化的json数组:

I've lots of json array which are formatted in this way:

[
   {
      "cod_ent":"953",
      "name_ent":"example1",
      "amb":{
         "15":{
            "cod_amb":"002",
            "name_amb":"Or11"
         },
         "1723":{
            "cod_amb":"00009",
            "name_amb":"P3o1"
         }
      }
   }
]

,我想在android中正确阅读.我尝试使用此代码,并且设法检索了前两个条目("cod_ent"和"name_ent"),但是我仍然无法管理"amb"子数组.

and i'd like to read it correctly in android. I try with this code and i manage to retrieve the first two entries ("cod_ent" and "name_ent") but i'm still not able to manage "amb" sub-array.

        JSONObject json = null;
        try {
            InputStream pre_json = response.getEntity().getContent();
            json = new JSONObject("{data:"+convertStreamToString(pre_json)+"}");
        } catch (IOException e) {
            e.printStackTrace();
        }

        JSONArray jsonArray = json.getJSONArray("data");
        for (int i = 0; i < jsonArray.length(); i++){
            JSONObject getfromarray = jsonArray.getJSONObject(i);
            cod_ent = getfromarray.getString("cod_ent");
            name_ent = getfromarray.getString("name_ent");

            //how to get amb???


        }

您可以像这样迭代JSONObject:

You can Iterate JSONObject Like this:

JSONObject jsonObject =getfromarray.getJSONObject("amb")
    Iterator<String> iter = jsonObject.keys();
    while (iter.hasNext()) {
        String key = iter.next();
        Log.w("Key", key);
        try {
            JSONObject js = jsonObject.getJSONObject(key);

            Log.w("cod_amb", js.getString("cod_amb"));
            Log.w("name_amb", js.getString("name_amb"));
        } catch (Exception e) {
            // TODO: handle exception
        }

    }