1. First introduce Gson class library to WebApp project
Copy to Webcontent/web-inf/lib
2. Doget returns 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 (ten);
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. Packaging and Publishing
4. Write client test code (parse the object by Gson)
public class Hellojava {public
static void Main (string[] args) {
//TODO auto-generated method stub
String ur L = "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;
}
Output results:
{"Name": "Bob Qin", "Sex": 1, "age": Ten, "email": "bob@hotmail.com", "Telephones": ["13813841385", "021-454566778"]}
Bob qin,bob@hotmail.com,10