Java servlet使用GSON返回JSON

1. 首先引入GSON类库到Webapp工程

复制到WebContent/WEB-INF/lib下

Java servlet使用GSON返回JSON_第1张图片


2. doGet返回JSON

protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("application/json");
		Person p = new Person();
		p.setAge(10);
		p.setEmail("[email protected]");
		p.setName("Bob Qin");
		p.setSex(Person.SEX_MAN);
		List<String> telephones = new ArrayList<String>();
		telephones.add("13813841385");
		telephones.add("021-454566778");
		p.setTelephones(telephones);
		PrintWriter writer = response.getWriter();
		writer.write(new Gson().toJson(p, Person.class));
		writer.flush();
	}
public class Person {
	public static final int SEX_MAN = 1;
	public static final int SEX_FEMALE = 2;
	public static final int SEX_UNKNOWN = 3;
	
	private String name;
	private int sex;
	private int age;
	private String email;
	private List<String> telephones;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getSex() {
		return sex;
	}
	public void setSex(int sex) {
		this.sex = sex;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public List<String> getTelephones() {
		return telephones;
	}
	public void setTelephones(List<String> telephones) {
		this.telephones = telephones;
	}
}


3. 打包发布

4. 编写客户端测试代码(通过GSON解析出Object)

public class HelloJava {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String url = "http://192.168.0.105/WhereAreYou/sayHello";
		String json = test(url);
		System.out.println(json);
		Person p = new Gson().fromJson(json, Person.class);
		System.out.println(p.getName() + "," + p.getEmail() + "," + p.getAge());
	}

	private static String test(String urlToRead) {
		URL url;
		HttpURLConnection conn;
		BufferedReader rd;
		String line;
		String result = "";
		try {
			url = new URL(urlToRead);
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			rd = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));
			while ((line = rd.readLine()) != null) {
				result += line;
			}
			rd.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;

	}
}

输出结果:

{"name":"Bob Qin","sex":1,"age":10,"email":"[email protected]","telephones":["13813841385","021-454566778"]}
Bob Qin,[email protected],10




你可能感兴趣的:(Java servlet使用GSON返回JSON)