简体   繁体   中英

Not parsing the array from json to android java

Why is it not parsing the array from json to android java, please help me to solve this problem? I want to show it's list view. How can i achieve this?

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

I want to show it's list view.

It's because you are using jsonObject in for loop. You need to get Employee jsonArray from that object and than iterate through it to get employee list as -

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM