Android json 数据解析
{"students":[{"sid":1001,"name":"zhangsan","addr":"Yichang","pic":"111.jpg"}, {"sid":1002,"name":"Jack","addr":"Beijing","pic":"222.jpg"}]}
{[{"sid":1001,"name":"zhangsan","addr":"Yichang","pic":"111.jpg"}, {"sid":1002,"name":"Jack","addr":"Beijing","pic":"222.jpg"}]}
Student stu = new Student(1005,"张三","Wuhan","zs.jpg");
JSONObject jsonObject = new JSONObject(stu);
JSONObject jsonObject = new JSONObject(str);
Iterator<String> iterator = jsonObject.keys();
Student stu = new Student();
while(iterator.hasNext()){
//可以利用java反射,写泛型方法
String key = iterator.next();
if(key.equals("sid")){
stu.setSid(jsonObject.getInt(key));
}
if(key.equals("name")){
stu.setName(jsonObject.getString(key));
}
if(key.equals("sid")){
stu.setAddr(jsonObject.getString(key));
}
if(key.equals("sid")){
stu.setPic(jsonObject.getString(key));
}
}
JSONObject jsonObject = new JSONObject();
jsonObject.put("zs", stu);
同样jsonObject.toString()就是字符串输出 {"zs":"{sid:1005, name:张三, addr:Wuhan, pic:zs.jpg}"}。要注意,如果Student没有覆写toString()方法,输入的是:{"zs":"org.itair.domain.Student@2666e815"}
Student s1 = new Student(1001,"zhangsan","yichang","111");
Student s2 = new Student(1002,"Jack","Beijing","222");
List<Student> stus = new ArrayList<Student>();
stus.add(s1);
stus.add(s2);
JSONArray array = new JSONArray(stus);
array的字符串是:[{"sid":1001,"name":"zhangsan","addr":"yichang","pic":"111"},{"sid":1002,"name":"Jack","addr":"Beijing","pic":"222"}]
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
//解析成特定的对象操作,new对象,从jsonObject2取出值来装进去
Iterator<String> iterator = jsonObject2.keys();
while (iterator.hasNext()) {
String key = iterator.next();
Object value = jsonObject2.get(key);
map.put(key, value);
}
}
Student s2 = new Student(1002,"Jack","Beijing","222");
List<Student> stus = new ArrayList<Student>();
stus.add(s1);
stus.add(s2);
JSONObject jsonObject = new JSONObject();
jsonObject.put("students", stus);
jsonObject的字符串:{"students":[{"sid":1001,"name":"zhangsan","addr":"yichang","pic":"111"},{"sid":1002,"name":"Jack","addr":"Beijing","pic":"222"}]}
JSONArray jsonArray = jsonObject.getJSONArray("key");//key就是上面放入的students
在Android的项目中,一般不会把Json字符串解析成对象的集合,而多是解析成List<Map<String,Object>>
List<Map<String,Object>> list = new ArrayList<Map<String ,Object>>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
Map<String ,Object> map = new HashMap<String, Object>();
Iterator<String> iterator = jsonObject2.keys();
while (iterator.hasNext()) {
String key = iterator.next();
Object value = jsonObject2.get(key);
map.put(key, value);
}
list.add(map);
}
要解析成对象集合,还是用Gson, fastjson比较方便。