Java Web return JSON tool class

Source: Internet
Author: User

Webthe project often involvesAJAXRequest returnJSONand theJSONPData。 Jsondata is transmitted on both the server and browser side, essentially transmitting strings, but this string conforms to theJSONsyntax format. The browser is received in normal text formatJSONstring, the finalJSONThe string is turned intoJSONobject throughJavaScriptimplementation. Currently some browsers(IE9the following browsers do not provide)and the usual JSLibraryhas been providedJSONmethods for serialization and deserialization, such as jqueryof theAJAXthe request can specify the format of the data returned, includingtext,JSON,Jsonp,XML,HTMLand so on.

Web server side as long as the Java object data into a JSON string, and the JSON string in the form of text The output can be response.

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[]{// Null value in the output map serializerfeature.writemapnullvalue,//if the Boolean object is null, The output is falseserializerfeature.writenullbooleanasfalse,//if list is null, the output is []serializerfeature.writenulllistasempty, If number is null, the output is 0serializerfeature.writenullnumberaszero,// Output NULL string serializerfeature.writenullstringasempty,//formatted output date serializerfeature.writedateusedateformat};/** * Serializing Java Object JSON * @param obj requires 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;/** * The request sends the callback parameter as the callback function, and the default callback function is used if no callback parameter is sent */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) {//If 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) {//If the client does not send a callback function, use the default callback function Responsejsonutils.jsonp (response, data);} else{//makesUsing 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) {//If 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);}}}



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java Web return JSON tool class

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.