Google gson

showServlet中

private String id;
private String pass;


protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {                                                                        
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
id = request.getParameter("id");
pass = request.getParameter("pass");
Gson gson = new Gson();
String json = gson.toJson(this);
out.println(json);
//------------------------------
showServlet obj = gson.fromJson(json,showServlet.class);
out.println(obj.getId());
out.println(obj.getPass());
}


index.jsp

 <form method="post" action="showServlet">
        帳號
        <input type="text" name="id" value=""/>
        密碼
        <input type="text" name="pass" value=""/>
        <input type="submit" value="ok"/>
 </form>

結果
{"id":輸入帳號id,"pass":輸入密碼pass}
{"id":"x123456","pass":"123456"}
//----------------------------------
帳號        密碼 
x123456 123456



處理中文亂碼      
  URL url = new URL("http://capture.heartrails.com/api/capture/free/?http://tw.yahoo.com");
            InputStream io = url.openStream();
            InputStreamReader a = new InputStreamReader(io, "UTF-8");
            int len;
            StringBuffer sb = new StringBuffer();
            while ((len = a.read()) != -1) {
                sb.append((char) len);
            }
            Gson gson = new Gson();
            jsonServlet obj = gson.fromJson(sb.toString(), jsonServlet.class);
   
            out.println(obj.getStatus());
            out.println(obj.getTitle());
            out.println(obj.getId());

Comments