json使用樣本

來源:互聯網
上載者:User

標籤:status   todo   轉換   ash   lock   hashmap   check   後台   ring   

 

(1)GsonMap map = new HashMap();map.put("id", "1");List list = new ArrayList();list.add("許海濤");list.add("陳淩霄");map.put("name", list);String json = new Gson().toJson(map);System.out.println(json);--> {"id":"1","name":["許海濤","陳淩霄"]}(2)JSONObject rootObj = new JSONObject();JSONArray array = new JSONArray();JSONObject temp = new JSONObject();try {    temp.put("id", "1");    temp.put("title", "title");    array.put(temp);    rootObj.put("allplus", array);} catch (JSONException e) {    // TODO Auto-generated catch block    e.printStackTrace();}System.out.println(rootObj);--> {"allplus":[{"id":"1","title":"title"}]}如果是json對象中放json數組還是用第2種方法好

 

String s = "{‘allplus‘:[{‘id‘:‘1‘,‘title‘:‘title‘}]}";JSONObject rootObj = new JSONObject(s);JSONArray array = rootObj.getJSONArray("allplus");for (int i = 0; i < array.length(); i++) {    JSONObject temp = array.getJSONObject(i);    System.out.println(temp.get("id") + "-->" + temp.get("title"));}

 

(1)public void doGet(HttpServletRequest request, HttpServletResponse response)        throws ServletException, IOException {    PrintWriter out = response.getWriter();    String userid = request.getParameter("userid");        int i = userDaoImpl.getCount(userid);    if (i == 1) {        String json = "{‘flag‘ : ‘true‘}";        out.print(json);    } else {        out.print("false");    }}注意:String json = "{‘flag‘ : ‘true‘}";      out.print(json);可以先寫好map,然後用Gson轉換為json格式,如下:Map map = new HashMap();map.put("flag", "true");String json = new Gson().toJson(map);out.print(json);(2)$("#uname").blur(function(){     var id = $("#uname").val();     $.ajax({       type: "POST",       url: "CheckServlet",       data: "userid=" + id,       success: function(data){          alert(data);           var obj = eval("("+data+")");          alert(obj.flag);          if (obj.flag == "true") {                            document.getElementById("msg").innerHTML = "使用者ID重複,無法使用!" ;              //alert("Data: " + data + "\nStatus: " + status);          }    else {              document.getElementById("msg").innerHTML = "此使用者ID可以註冊!" ;              //alert("Data: " + data + "\nStatus: " + status);          }       }     })})注意點:接收後台傳遞的json參數時,var obj = eval("("+data+")"); 必須要eval加括弧。唯寫eval(data)還不行。

 

json使用樣本

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.