使用gson进行json转换

Gson 是 Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库。可以将一个 JSON 字符串转成一个 Java 对象,或者反过来。
示例代码如下:

实体定义

package com.wisdombud.gson;

public class SimpleEntity {

	private String testInfo;

	private Boolean result;

	public String getTestInfo() {
		return testInfo;
	}

	public void setTestInfo(String testInfo) {
		this.testInfo = testInfo;
	}

	public Boolean getResult() {
		return result;
	}

	public void setResult(Boolean result) {
		this.result = result;
	}
}

package com.wisdombud.gson;

import java.util.List;

public class ComplexEntity {
	private List<SimpleEntity> list;
	
	private String name;
	
	private int age;

	public List<SimpleEntity> getList() {
		return list;
	}

	public void setList(List<SimpleEntity> list) {
		this.list = list;
	}

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

核心代码

package com.wisdombud.gson;

import java.util.ArrayList;
import java.util.List;

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

public class App {
	public static void main(String[] args) {
		String s = test2Json();
		System.out.println(s);
		testFromJson();
	}

	private static String test2Json() {
		Gson g = new Gson();
		List<ComplexEntity> cList = new ArrayList<ComplexEntity>();

		ComplexEntity entity = new ComplexEntity();
		cList.add(entity);
		entity.setAge(10);
		entity.setName("name");
		List<SimpleEntity> list = new ArrayList<SimpleEntity>();
		entity.setList(list);
		SimpleEntity simple = new SimpleEntity();
		simple.setResult(true);
		simple.setTestInfo("testinfo");
		list.add(simple);

		String s = g.toJson(cList);

		return s;
	}

	public static void testFromJson() {

		String json = test2Json();
		Gson g = new Gson();
		List<SimpleEntity> list = g.fromJson(json,
				new TypeToken<List<SimpleEntity>>() {
				}.getType());

		System.out.println(list.size());
	}
}

posted @ 2015-05-25 21:33  wardensky  阅读(397)  评论(0编辑  收藏  举报