将数组从json解析

将数组从json解析

为什么不将数组从json解析为android java,请帮助我解决此问题?我想显示它的列表视图。我怎样才能做到这一点?

String strJson="{\"Employee\":[{\"id\":\"101\",\"name\":\"Pushkar\",\"salary\":\"5000\"},{\"id\":\"102\",\"name\":\"Rahul\",\"salary\":\"4000\"},{\"id\":\"103\",\"name\":\"tanveer\",\"salary\":\"56678\"}]}";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        final ArrayList<String> item = new ArrayList<String>();
        final ArrayList<Employee> employ = new ArrayList<Employee>();
        String data;

        try {
            JSONObject jsonObject = new JSONObject(strJson);
             //jsonArray = new JSONArray(strJson);
             // Log.d("jsonArrayLength: ", "Length: "+ jsonObject.length());

            for (int i = 0; i < jsonObject.length(); i++) {
                Employee emp = new Employee();
                String name = jsonObject.getString("name");
                String id = jsonObject.getString("id");
                String salary = jsonObject.getString("salary");
                emp.setId(id);
                emp.setName(name);
                emp.setSalary(salary);
                item.add(i,name);
                employ.add(i,emp);
            }

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


我想显示它的列表视图。

最佳答案

这是因为您在for循环中使用了jsonObject。您需要从该对象获取Employee jsonArray,然后对其进行遍历以获取雇员列表为-

 try {
        JSONObject jsonObject = new JSONObject(strJson);
        JSONArray jsonArr = jsonObject.getJSONArray("Employee");
        Log.d("jsonArrayLength: ", "Length: "+ jsonArr.length());

        for (int i = 0; i < jsonArr.length(); i++) {
            Employee emp = new Employee();
            JSONObject empObj = jsonArr.getJSONObject(i);
            String name = empObj.getString("name");
            String id = empObj.getString("id");
            String salary = empObj.getString("salary");
            emp.setId(id);
            emp.setName(name);
            emp.setSalary(salary);
            item.add(i,name);
            employ.add(i,emp);
        }

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

08-17 21:28