如何解析二级JSON数组

时间:2014-06-20 10:59:23

标签: android json parsing

我正在关注this教程来解析JSON数据

现在我知道如何使用单个JSON数组解析简单的JSON,但现在我必须解析多级JSON

就像我能够解析第一级列表但不知道如何解析第二级,请参阅下面的JSON格式:

{
            "batches": [
                {
                    "title": "Beginners",
                    "students": [
                        {
                            "name": "Jack"
                        },
                        {
                            "name": "Lam"
                        },
                        {
                            "name": "Temp"
                        }
                    ]
                },
                {
                    "title": "Intermediate",
                    "students": [
                        {
                            "name": "Ashta"
                        }
                    ]
                },
                {
                    "title": "Advance",
                    "students": [
                        {
                            "name": "Kamak"
                        },
            {
                            "name": "Basi"
                        }
                    ]
                }
            ]
        }

我的第一级JSON解析结果如下:

  

初​​学者

     

中间体

     

高级

现在我希望每当用户点击初学者时需要列出他们的记录:

  

杰克

     

     

温度

MainActivity.java: -

public class MainActivity extends ActionBarActivity {
    ProgressDialog progressDialog;
    JSONObject jsonObject;
    JSONArray jsonArrayBatches, jsonArrayStudents;
    ArrayList<HashMap<String, String>> arrayList;
    ListView listView;
    ListViewAdapter listViewAdapter;
    static String NODE_BATCH_TITLE = "title";
    static String NODE_STUDENT_NAME = "name";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listview_main);
        // execute AsyncTask
        new JSONData().execute();
    }

    private class JSONData extends AsyncTask<Void, Void, Void>
    {

        protected void onPreExecute()
        {
            super.onPreExecute();           
            progressDialog = new ProgressDialog(MainActivity.this);
            progressDialog.setIcon(R.drawable.ic_launcher);
            progressDialog.setTitle("JSON Parsing");
            progressDialog.setMessage("Loading...");
            progressDialog.show();
            Log.d("onPreExecute()::", "onPreExecute()");
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // TODO Auto-generated method stub
            Log.d("doInBackground()::", "doInBackground()");
            // initializing ArrayList
            arrayList = new ArrayList<HashMap<String, String>>();

            jsonObject = JSONParsing.getJSONfromURL("URL");
            try {

                // locate the array name in JSON
                jsonArrayBatches = jsonObject.getJSONArray("batches");
                // using for loop to get the length of json array
                for (int b = 0; b < jsonArrayBatches.length(); b++) {
                    // get the each and every json object from array
                    jsonObject = jsonArrayBatches.getJSONObject(b);
                    // name,value pair
                    HashMap<String, String> hashMapBatches = new HashMap<String, String>();
                    // put data into HashMap & convert json object to string
                    hashMapBatches.put("title", jsonObject.getString("title")); // node name = name (in JSON)                   
                    // add HashMap to ArrayList
                    arrayList.add(hashMapBatches); 
                }
                // locate the array name in JSON
                jsonArrayStudents = jsonObject.getJSONArray("students");
                // using for loop to get the length of json array
                for (int b = 0; b < jsonArrayBatches.length(); b++) {
                    // get the each and every json object from array
                    jsonObject = jsonArrayBatches.getJSONObject(b);
                    // name,value pair
                    HashMap<String, String> hashMapBatches = new HashMap<String, String>();
                    // put data into HashMap & convert json object to string
                    hashMapBatches.put("name", jsonObject.getString("name")); // node name = name (in JSON)                 
                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

        protected void onPostExecute(Void args)
        {
            // reference to ListView
            listView = (ListView) findViewById(R.id.listview);
            // put ArrayList to Adapter
            listViewAdapter = new ListViewAdapter(MainActivity.this, arrayList);
            // set Adapter to ListView
            listView.setAdapter(listViewAdapter);
            progressDialog.dismiss();
            Log.d("onPostExecute()::", "onPostExecute()");

            listView.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                        int position, long arg3) {
                    // TODO Auto-generated method stub
                    Toast.makeText(MainActivity.this, arrayList.get(position).get(MainActivity.NODE_STUDENT_NAME), Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                    startActivity(intent);
                }
            });
        }

    }
}

SecondActivity.java: -

public class SecondActivity extends ActionBarActivity {

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listview_main);
    }

}

3 个答案:

答案 0 :(得分:1)

试试这个...

//first level 
jsonArrayBatches = jsonObject.getJSONArray("batches");
        // using for loop to get the length of json array
        for (int b = 0; b < jsonArrayBatches.length(); b++) {
            // get the each and every json object from array
            jsonObject = jsonArrayBatches.getJSONObject(b);
            // name,value pair
            HashMap<String, String> hashMapBatches = new HashMap<String, String>();
            // put data into HashMap & convert json object to string
            // hashMapBatches.put("title", jsonObject.getString("title"));

                    //Second level 
                JSONArray json_second = new JSONArray("students");
                for (int i=0;i<json_second.length();i++)
                {
                     JSONObject jsonObject = json_second.getJSONObject(i);
                     String name = jsonObject.getString("name");
                             hashMapBatches.put("name", name);
                }
           }

答案 1 :(得分:1)

你好你可以在这里查看并按照解决方案和正确的方式来处理JSON ..

1。MainActivity

2。SecondActivity

3。FirstListAdapter

4。SecondListAdapter

你可以在这里理解完整的JSON解析..

答案 2 :(得分:0)

首先,您不必使用现成的答案,您必须使用此链接了解JSON。

JSON LINK。因为你必须准确理解你想用JSON做什么。 和

验证你的JSON和识别哪个是JSON字符串,JSON数组,JSON对象我建议你使用

JSON Formate,在这里你必须传递你的JSON数据或使用实时URL并检查哪一个是数组,对象和字符串。