您好我是Android新手,正在处理一个片段,我将json数据作为
{"students":[{"id":"26","name":"aaa","abbr":"A"},{"id":"27","name":"bbb","abbr":"B"},{"id":"28","name":"ccc","abbr":"C"}]}
我希望将此记录设为单行,例如id=26,name="aaa",abbr="A"
JSONObject json;
JSONArray jsonarray_student;
ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
jsonarray_student = json.getJSONArray("students");
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", json.getString("id"));
map.put("name", json.getString("name"));
map.put("abbr", json.getString("abbr"));
arraylist.add(map);
地图会给我所有id的所有名称和所有abbr的 我需要将它们存储在List iterate ???
中答案 0 :(得分:0)
请尝试这种方式,希望这有助于您解决问题。
String response = "{\"students\":[{\"id\":\"26\",\"name\":\"aaa\",\"abbr\":\"A\"},{\"id\":\"27\",\"name\":\"bbb\",\"abbr\":\"B\"},{\"id\":\"28\",\"name\":\"ccc\",\"abbr\":\"C\"}]}}";
try{
ArrayList<HashMap<String, String>> studentList = new ArrayList<HashMap<String, String>>();
JSONObject responeJsonObject = new JSONObject(response);
JSONArray studentsJsonArry = responeJsonObject.getJSONArray("students");
for (int i=0;i<studentsJsonArry.length();i++){
HashMap<String, String> studentData = new HashMap<String, String>();
studentData.put("id", studentsJsonArry.getJSONObject(i).getString("id"));
studentData.put("name", studentsJsonArry.getJSONObject(i).getString("name"));
studentData.put("abbr", studentsJsonArry.getJSONObject(i).getString("abbr"));
studentList.add(studentData);
}
for (HashMap<String,String> student : studentList){
System.out.print("id"+student.get("id"));
System.out.print("name"+student.get("name"));
System.out.print("abbr"+student.get("abbr"));
}
}catch (Throwable e){
e.printStackTrace();
}
答案 1 :(得分:0)
是有一种方法可以让你排成一行,我最喜欢的是Gson Libray的使用,这将允许你解析你的字符串并得到一个对象列表& #34;学生&#34; (列表)你只需要做的事情:
TextView id = (TextView) findViewById(R.Id.textview);
TextView name = (TextView) findViewById(R.Id.textview);
TextView abbr = (TextView) findViewById(R.Id.textview);
id.setText(student.getId());
name.setText(student.getName());
abbr.setText(student.getAbbr());
学生是名单中的条目
希望这可以帮助你解决问题=)