Java Web return JSON

Source: Internet
Author: User
Tags java web

Webthe project often involvesAJAXRequest returnJSONand theJSONPData。 Jsondata is transmitted on both the server side and the browser side, essentially transmitting a string, except that the string conforms to theJSONsyntax format. The browser will be received in plain text formatJSONstring. FinallyJSONThe string is turned intoJSONobject throughJavaScriptimplementation. Some browsers now(IE9The following browser does not provide)And often-used JSLibraryhas been providedJSONmethods for serialization and deserialization。 such as jqueryof theAJAXthe request is able to specify the returned data format, includingtext,JSON,Jsonp,XML,HTMLand so on.

the WEB server side simply turns the Java object data into a JSON string. and the JSON string in the form of text through the response output can be.

Import Java.io.ioexception;import Java.io.printwriter;import Javax.servlet.http.httpservletresponse;import Com.alibaba.fastjson.json;import com.alibaba.fastjson.serializer.serializerfeature;/** * * Web service side return JSON Tool class * Tool class Dependent Fastjson * Tool class supports returning JSON and JSONP format data * @author [email protected] * */public class Responsejsonutils {/** * default character encoding * /private static string encoding = "UTF-8";/** * Jsonp default callback function */private static string callback = "Callback";/** * Fastjson Serialization settings */private static serializerfeature[] features = new serializerfeature[]{// The null value in the output map serializerfeature.writemapnullvalue,//assumes that the Boolean object is null. The output is falseserializerfeature.writenullbooleanasfalse,//assuming the list is null. The output is []serializerfeature.writenulllistasempty,//assumes that number is null. The output is 0serializerfeature.writenullnumberaszero,//output null string serializerfeature.writenullstringasempty,// Formatted output Date serializerfeature.writedateusedateformat};/** * Serializing Java Object JSON * @param obj JSON-serialized Java Object * @return JSON String */ private static String tojsonstring (Object obj) {return json.tojsonstring (obj, features);} /** * Returns JSON formatted DATA * @param response * @param data to return Java Object * @param encoding returns the encoded format of the JSON string */public the static void json (HTT Pservletresponse response, Object data, String encoding) {//Set encoding format response.setcontenttype ("text/plain;charset=" + encoding); response.setcharacterencoding (encoding); PrintWriter out = Null;try{out = Response.getwriter (); Out.write (tojsonstring (data)); Out.flush ();} catch (IOException e) {e.printstacktrace ();}}  /** * Returns JSON formatted data using the default encoding * @param response * @param data to return Java object */public static void json (HttpServletResponse response, Object data) {JSON (response, data, encoding);} /** * Returns JSONP data using default encoding and default callback function * @param response * @param data jsonp */public static void Jsonp (HttpServletResponse respo NSE, Object data) {JSONP (response, callback, data, encoding);} /** * Returns JSONP data, using default encoding * @param response * @param callback JSONP callback function name * @param data jsonp */public static void Jsonp (Ht Tpservletresponse response, String callback, Object data) {JSONP (response, callback, data, encoding);}  /** * Return JSONP Data * @param response * @param callback JSONP callback function name * @param data JSONP * @param encoding JSONP data encoding */public static void Jsonp (HttpServletResponse response, String callback, Object data, string encoding) {StringBuffer SB = new Stri Ngbuffer (callback), Sb.append ("("); Sb.append (tojsonstring (data)); Sb.append (");"); /Set Encoding format response.setcontenttype ("text/plain;charset=" + encoding); response.setcharacterencoding (encoding); PrintWriter out = null;try {out = Response.getwriter (); Out.write (sb.tostring ()); Out.flush ();} catch (IOException e) { E.printstacktrace ();}} public static String GetEncoding () {return encoding;} public static void Setencoding (String encoding) {responsejsonutils.encoding = encoding;} public static String Getcallback () {return callback;} public static void Setcallback (String callback) {responsejsonutils.callback = callback;}}

/** * Return JSON data in servlet */@WebServlet ("/json.do") public class Jsonservlet extends HttpServlet {private static final long SE Rialversionuid = 7500835936131982864l;/** * Returns JSON-formatted data */protected void Service (HttpServletRequest request, HttpServletResponse response) throws Servletexception, IOException {map<string, object> data = new hashmap< String, object> ();d ata.put ("date", new Date ());d ata.put ("email", "[email protected]");d ata.put ("age", 30); Data.put ("name", "Csdn");d ata.put ("array", new int[]{1,2,3,4}); Responsejsonutils.json (response, data);}}

/** * servlet returns JSONP format data */@WebServlet ("/jsonp.do") public class Jsonpservlet extends HttpServlet {private static final lo ng Serialversionuid = -8343408864035108293l;/** * Request sends callback as a callback function, assuming that no callback parameters are sent use the default callback function */protected void Service (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {// The callback function sent by the client string callback = Request.getparameter ("callback"); map<string, object> data = new hashmap<string, object> ();d ata.put ("date", new Date ());d ata.put ("email", "[ Email protected]);d ata.put ("Age", "a");d ata.put ("name", "Csdn");d ata.put ("array", new int[]{1,2,3,4}); if (callback = = null | | Callback.length () = = 0) {//Suppose the client does not send a callback function. Use the default callback function Responsejsonutils.jsonp (response, data);} ELSE{//uses the client's callback function Responsejsonutils.jsonp (response, callback, data);}}}

/** * Back in Struts2 JSON and Jsonp */public class Jsonaction extends Actionsupport {private static final long Serialversionuid = 5391000845385666048l;/** * JSONP callback function */private String callback;/** * return json */public void json () {HttpServletResponse res Ponse = Servletactioncontext.getresponse (); map<string, object> data = new hashmap<string, object> ();d ata.put ("date", new Date ());d ata.put ("email", "[ Email protected] ");d ata.put (" Age "," a ");d ata.put (" name "," Csdn ");d ata.put (" array ", new int[]{1,2,3,4}); Responsejsonutils.json (response, data);} /** * returns Jsonp */public void Jsonp () {HttpServletResponse response = Servletactioncontext.getresponse (); map<string, object> data = new hashmap<string, object> ();d ata.put ("date", new Date ());d ata.put ("email", "[ Email protected] ");d ata.put (" Age "," a ");d ata.put (" name "," Csdn ");d ata.put (" array ", new int[]{1,2,3,4}); callback = = NULL | | Callback.length () = = 0) {//Assuming the client does not send a callback function, use the default callback function Responsejsonutils.jsonp (response, data);} else{Use the client's callback function Responsejsonutils.jsonp (response, callback, data);}} Public String Getcallback () {return callback;} public void Setcallback (String callback) {this.callback = callback;}}

Import Org.springframework.stereotype.controller;import org.springframework.web.bind.annotation.requestmapping;/ * * * Spring MVC returns JSON and JSONP data */@Controller @requestmapping ("/json") public class Jsoncontroller {/** * return JSON data * @param re Quest * @param response */@RequestMapping ("/json.do") public void JSON (HttpServletRequest request, HttpServletResponse Response) {map<string, object> data = new hashmap<string, object> ();d ata.put ("date", new Date ());d ata.put (" Email ", [email protected]");d ata.put ("Age", "a");d ata.put ("name", "Csdn");d ata.put ("array", New int[]{1,2,3,4} ); Responsejsonutils.json (response, data);} /** * Returns JSONP data * @param callback JSONP callback function * @param request * @param response */@RequestMapping ("/jsonp.do") public void JSON (String callback, HttpServletRequest request, httpservletresponse response) {map<string, object> data = new Hashmap<string, object> ();d ata.put ("date", new Date ());d ata.put ("email", "[email protected]");d Ata.put ( "Age",;d ata.put ("Name", "Csdn");d ata.put ("array", new int[]{1,2,3,4}); if (callback = = NULL | | callback.length () = = 0) {//Assuming the client does not send a callback function , the default callback function Responsejsonutils.jsonp (response, data) is used;} ELSE{//uses the client's callback function Responsejsonutils.jsonp (response, callback, data);}}}



Java Web return JSON

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.