1. 首先引入GSON類庫到Webapp工程
複製到WebContent/WEB-INF/lib下
2. doGet返回JSON
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubresponse.setContentType("application/json");Person p = new Person();p.setAge(10);p.setEmail("bob@hotmail.com");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 stubString 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":"bob@hotmail.com","telephones":["13813841385","021-454566778"]}Bob Qin,bob@hotmail.com,10