日期:2014-05-16  浏览次数:20407 次

简单的JSON解析

用google-gson来解析json,jar包附件中

方法1:

import java.io.StringReader;
import com.google.gson.stream.JsonReader;

public class JsonUtils {
	public void parseJson(String jsonData){
		try{
			//如果需要解析JSON数据,首要要生成一个JsonReader对象
			JsonReader reader = new JsonReader(new StringReader(jsonData));
			reader.beginArray();
			while(reader.hasNext()){
				reader.beginObject();
				while(reader.hasNext()){
					String tagName = reader.nextName();
					if(tagName.equals("name")){
						System.out.println("name--->" + reader.nextString());
					}
					else if(tagName.equals("age")){
						System.out.println("age--->" + reader.nextInt());
					}
				}
				reader.endObject();
			}
			reader.endArray();
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
}

json就是字符串:
String jsonData = "[{\"name\":\"Michael\",\"age\":20},{\"name\":\"Mike\",\"age\":21}]";

?方法2.1:把json转化为java对象(单个对象!)

要转化成的对象:

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;
	}
}

?解析:

import com.google.gson.Gson;


public class JsonUtils {
	
	public void parseUserFromJson(String jsonData){
		Gson gson = new Gson();
		User user = gson.fromJson(jsonData, User.class);
		System.out.println("name--->" + user.getName());
		System.out.println("age---->" + user.getAge());
		
	}
}

其中String jsonData = "{\"name\":\"Michael\",\"age\":20}";

?方法2.2:把json转化为java对象数组!

1.要转化成的对象还是上面的User类对象。

2.解析;

import java.lang.reflect.Type;
import java.util.Iterator;
import java.util.LinkedList;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;


public class JsonUtils {
	
	public void parseUserFromJson(String jsonData){
		Type listType = new TypeToken<LinkedList<User>>(){}.getType();
		Gson gson = new Gson();
		LinkedList<User> users = gson.fromJson(jsonData, listType);
		for (Iterator iterator = users.iterator(); iterator.hasNext();) {
			User user = (User) iterator.next();
			System.out.println("name--->" + user.getName());
			System.out.println("age---->" + user.getAge());
		}
		
	}
}

?其中String jsonData = "[{\"name\":\"Michael\",\"age\":20},{\"name\":\"Mike\",\"age\":21}]";