JSON is a good thing, is a third-party library too many have wood. Today in the conversion list into JSON, the method found on the Internet, the use of a variety of third-party libraries, to stun themselves, in fact, is very simple. So when doing things must be clear thinking, import of the package is also very important, do not come up to see the code, the whole circle of their own ... Before the use of Google's Gson, this time with Ali's Fastjson.
The project uses a servlet.
//ensure that the JSP and servlet are encoded in the same wayResp.setcontenttype ("TEXT/HTML;CHARSET=GBK"); List<String> jymdlist =NewArraylist<string>(); PrintWriter out=NULL; Try { //get list from databaseJymdlist =Efileviewuiservice.getlymd (); //this sentence on the conversion, tossing me for a long time, simple rough, for map This sentence also appliesString JSON =json.tojsonstring (jymdlist); //get flow to JSP pass dataPrintWriter out =Resp.getwriter (); Out.print (JSON); } Catch(baseexception e) {e.printstacktrace (); } finally{out.close (); }
followed by a JSP, with jquery
$ (function () {$.ajax ({ URL: "<%=basepath%>/servlet?cmd=getjymd&random=" +math.random (), Type: "POST" " JSON ", success: function (data) { $.each (data, function {$ (name, value) {$ ( "#remark" <option> +value + "</option>" ); }); } }); });
The cmd after the URL question mark is req.getparameter ("cmd") in the servlet and then judged, in determining which method to invoke.
After that, the jquery each corresponds to a for loop, and a select selects the value into option.
Convert list and map to JSON using Fastjson