Android Json解析 - 初步
if(country.equals(theKey))
{
System.out.println(reader.nextString());
}
if(province.equals(theKey))
{
System.out.println(reader.nextString());
}
if(city.equals(theKey))
{
System.out.println(reader.nextString());
}
}
reader.endObject();
}
}
reader.endObject();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
都給解析出來了。
1.解析一個對象
可以直接從Json中將隊形解析出來,這個Json必須是一個Json對象,如下:
{name:zhangsan,age:22,address:太原}
它只是一個對象。
我新建一個類,生成get和set方法,如下:
package com.zhycheng;
publicclass Human {
String name,address;
int age;
public String getName() {
return name;
}
publicvoid setName(String name) {
this.name = name;
}
publicint getAge() {
return age;
}
publicvoid setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
publicvoid setAddress(String address) {
this.address = address;
}
}
然后使用如下代碼直接解析
String s={name:zhangsan,age:22,address:太原};
Gson g=new Gson();
Human h=g.fromJson(s, Human.class);
System.out.println(h.getName()+;+h.getAge()+;+h.getAddress());
2.解析數(shù)組
下面解析如下的Json數(shù)據(jù):
[{name:zhangsan,age:22,address:太原},
{name:lisi,age:20,address:黃岡},
{name:wangwu,age:21,address:武漢}]
代碼如下:
String s=[{name:zhangsan,age:22,address:太原},{name:lisi,age:20,address:黃岡},{name:wangwu,age:21,address:武漢}];
Type type=new TypeToken>(){}.getType();
Gson g=new Gson();
LinkedList ll=g.fromJson(s, type);
for(int i=0;i
{
Human h=(Human)ll.get(i);
System.out.println(h.getName()+,+h.getAge()+,+h.getAddress());
}
在這里要注意:
1.Json里的數(shù)據(jù)時數(shù)組,數(shù)組里是對象
2.泛形一定要用,否則出錯
項目工程下載。
評論