(1) Gsonmap Map=NewHashMap (); Map.put ("id", "1"); List List=NewArrayList (); List.add ("Xu Haitao"); List.add ("Sky Chen"); Map.put ("Name", list); String JSON=NewGson (). ToJson (map); SYSTEM.OUT.PRINTLN (JSON);--{"id": "1", "Name": ["Xu Haitao", "Sky Chen"]}(2) Jsonobject Rootobj=NewJsonobject (); Jsonarray Array=NewJsonarray (); Jsonobject Temp=NewJsonobject ();Try{temp.put ("id", "1"); Temp.put ("title", "title"); Array.put (temp); Rootobj.put ("Allplus", array);} Catch(jsonexception e) {//TODO auto-generated Catch blocke.printstacktrace ();} System.out.println (rootobj);--{"Allplus": [{"id": "1", "title": "title"}]} If it is a JSON object to put in a JSON array or a 2nd method of good
String s = "{' Allplus ': [{' id ': ' 1 ', ' title ': ' Title '}]}"new= Rootobj.getjsonarray ("Allplus "); for (int i = 0; i < array.length (); i++) { = array.getjsonobject (i) ; System.out.println (Temp.get ("id") + "-" + temp.get ("title");}
(1) Public voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {printwriter out=Response.getwriter (); String userid= Request.getparameter ("userid"); inti =Userdaoimpl.getcount (userid); if(i = = 1) {String json= "{' flag ': ' True '}"; Out.print (JSON); } Else{out.print ("False"); }} Note: String JSON= "{' flag ': ' True '}"; Out.print (JSON); You can write the map first and then convert it to JSON format using Gson, as follows: Map map=NewHashMap (); Map.put ("Flag", "true"); String JSON=NewGson (). 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 = "User ID is duplicated and cannot be used!" " ; //alert ("Data:" + Data + "\nstatus:" + status);}Else{document.getElementById ("MSG"). InnerHTML = "This user ID can be registered!" " ; //alert ("Data:" + Data + "\nstatus:" + status);(}}) }) Note: When receiving JSON parameters for background delivery, Var obj= eval ("(" +data+ ")"); You must have the eval brackets. Writing only eval (data) is not enough.
JSON usage examples