Java servlet使用GSON返回JSON__PHP

來源:互聯網
上載者:User

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




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.