json解析
一、解析json
准备工作:导入gson的jar包
下载地址:http://code.google.com/p/google-gson/
二、解析
1、 使用JsonReader
示例代码如下:
//json数据为json="[{\"name\":\"guoxu\",\"age\":25},{\"name\":\"lisi\",\"age\":25}]";
public class JsonUtil {
public void Parse(String jsonData){
JsonReader json=new JsonReader(new StringReader(jsonData));
try {
//开始数组解析
json.beginArray();
while(json.hasNext()){
//开始对象解析
json.beginObject();
while(json.hasNext()){
String targetName=json.nextName();
//开始键值解析
if(targetName.equals("name")){
System.out.println("name="+json.nextString());
}else if(targetName.equals("age")){
System.out.println("age="+json.nextInt());
}
}
json.endObject();
}
json.endArray();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2.使用Gson
示例代码如下:
//String json="{\"name\":\"guoxu\",\"age\":25}";
public class JsonUtil {
public void Parse(String jsonData){
Gson gson=new Gson();
User user=gson.fromJson(jsonData, User.class);
System.out.println(user.getName());
System.out.println(user.getAge());
}
}
User对象:
public class User {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
3、 更复杂的应用:
//json="[{\"name\":\"guoxu\",\"age\":25},{\"name\":\"lisi\",\"age\":25}]";
public class JsonUtil {
public void Parse(String jsonData){
Type listType=new TypeToken<LinkedList<User>>(){}.getType();
Gson gson=new Gson();
LinkedList<User> users=gson.fromJson(jsonData, listType);
for (Iterator<User> iterator = users.iterator(); iterator.hasNext();) {
User user = (User) iterator.next();
System.out.println(user.getName());
System.out.println(user.getAge());
}
}
}
User对象:
package org.demo.json1;
public class User {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}