为什么它不能将数组从 json 解析为 android java,请帮我解决这个问题?我想显示它的 ListView 。我怎样才能实现这个目标?
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();}
}
我想显示它的 ListView 。
最佳答案
这是因为您在 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();
}
关于java - 不将数组从 json 解析为 android java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58363856/