Gson解析json,比Json-lib更加的方便

public class ParseJson {
	String json1 = "{\"name\":\"gaofeng\",\"age\":\"20\"}";
	String json2 = "{\"total\":\"100\",\"rows\":[{\"name\":\"张三\",\"age\":\"20\"},{\"name\":\"李四\",\"age\":\"22\"}]}";

	/**
	 * ParseJson类介绍如何解析不同类型的json格式的数据
	 * test1格式比较简单
	 * test2格式稍微复杂点
	 * */
	@Test
	public void test1() {
		// 需要解析的json数据
		System.out.println("json1:" + json1);
		Gson gson = new Gson();
		rows json_data=gson.fromJson(json1, rows.class);
		
		System.out.println("Age:"+json_data.getAge()+"  Name:"+json_data.getName());		
		System.out.println("~~~~~~~~~~~~~~~~");
  
	}

	@Test
	public void test2() {
		// 需要解析的json数据
		System.out.println("json2:" + json2);
		Type type = new TypeToken<mess>() {}.getType();
		
		Gson gson = new Gson();
		mess mess_info = gson.fromJson(json2, type);
		System.out.println("total:"+mess_info.getTotal());
		System.out.println("rows的值:"+mess_info.getRows().size());
		for (int i = 0; i < mess_info.getRows().size(); i++) {
			System.out.println("第"+(i+1)+"轮:");
			System.out.println("Name:" + mess_info.getRows().get(i).getName()+"  Age:" + mess_info.getRows().get(i).getAge());			
		}
	}
}


映射对象类:

<span style="font-size:14px;">public class mess {
	private int total;
	private List<rows> rows;

	public int getTotal() {
		return total;
	}
	public void setTotal(int total) {
		this.total = total;
	}
	public List<rows> getRows() {
		return rows;
	}
	public void setRows(List<rows> rows) {
		this.rows = rows;
	}
}</span>
public class rows {

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

}
输出的结果:

json1:{"name":"gaofeng","age":"20"}
Age:20  Name:gaofeng
~~~~~~~~~~~~~~~~
json2:{"total":"100","rows":[{"name":"张三","age":"20"},{"name":"李四","age":"22"}]}
total:100
rows的值:2
第1轮:
Name:张三  Age:20
第2轮:
Name:李四  Age:22


发布了38 篇原创文章 · 获赞 22 · 访问量 16万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章