Java Web program implementation returns a JSON string method summary _java

Source: Internet
Author: User
Tags comments documentation serialization java web stringbuffer

Foundation Bedding
in Java, there are a lot of lib for JSON, such as Jackjson, Fastjson, Gson, and so on, which I've used, but it's too onerous for programmers like me who just want the Java object to return to the JSON string. And some features are very poor customization, such as a Java object's properties are empty, these components will not output, so I cycle through the page list object, always have to judge whether this attribute is undefined, which makes me very dissatisfied. So decide to spend some time studying what's going on.

But after a morning of scrutiny, found that either Fastjson or Gson code are written quite complex, and there is no relevant documentation and comments, finally gave up. So I found a relatively simple Java package to return JSON on the www.json.com, this lib only needs 5 Java classes to run, it is my intention. It should be noted that the official Jsonarray this thing does not support the direct conversion of JavaBean, such as list<user> such things can not be converted, it must be converted to list<map> such a format, in order to convert, So I did a makeover on it. The official documents are:

Introduce the basic usage first.

Working with basic Java objects uses the Jsonobject class, which is generally as follows:

public void TestMap () {
    map<string,object> Map = new hashmap<string,object> ();
    Map.put ("name", "Qiu");
    Map.put ("password", "123");
    Map.put ("Address", "a");
    
    User user = new user ();
    User.setusername ("Qiuqiu");
    User.setpassword ("123456");
    User.gettels (). Add ("1234444556677");
    User.gettels (). Add ("6893493458585");
    
    Map.put ("user", user);
    
    Jsonobject json = new Jsonobject (map);
    System.out.println (Json.tostring ());
  }

In the case of a collection object, the Jsonarray class is used, as follows:

public void Testlist () throws jsonexception{
    list<user> List = new arraylist<user> ();
    
    User user = new user ();
    User.setusername ("Qiuqiu");
    User.setpassword ("123456");
    User.gettels (). Add ("1234444556677");
    User.gettels (). Add ("6893493458585");
    
    User User2 = new user ();
    User2.setusername ("China");
    User2.gettels (). Add ("1234444556677");
    User2.gettels (). Add ("6893493458585");
    
    List.add (user);
    List.add (user2);
    
    Jsonarray json = new Jsonarray (list);
    
    System.out.println (json.tostring (2));
  }

From the above code can be seen, the use of the Lib is quite simple, unlike what Gson to create new objects, Fastjson API design is also somewhat unreasonable. In the second paragraph above, there is a ToString (2) that indicates the output is indented two spaces by line break.
It's just a basic usage, but it's not what you want, but what you want to do is to return an empty string when the object property is empty, instead of returning nothing. Although only 5 classes, but I still spent two or three hours to find a place, in the Jsonobject has a method called Populatemap, at the end of a small piece of code:

Object result = Method.invoke (Bean, (object[]) null);
 if (result!= null) {
   this.map.put (key, wrap (result));
 }

This property is not exported when the call to the GET method returns NULL. Of course, the change is very simple:

Object result = Method.invoke (Bean, (object[]) null);
This.map.put (Key, Result==null? "": Wrap (result));

This finally solved the problem I want to solve. Of course this lib is the official band of JSON, written quite simple, more suitable for a data only a few or dozens of cases, such as paging display. If the amount of data transmitted at one time is large, you can consider using Fastjson and so on. But personally feel that for most occasions, the most needed is customization. For example, occasionally found that a component can not meet the needs, the result of this component is no documentation and no comments, the code is more difficult to understand, basically with no open source almost, it doesn't make sense.

Example Summary

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 server return JSON Tool class * Tool class Dependency Fastjson * Tool class support returns JSON and JSONP format data * @author accountwcx@qq.com * */public CLA 
   
  SS 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[]{//output map for Nu ll's value serializerfeature.writemapnullvalue,//If the Boolean object is null, the output is false Serializerfeature.writenullboo  
    Leanasfalse,//If list is null, output is [] serializerfeature.writenulllistasempty,//If number is null, output is 0 
Serializerfeature.writenullnumberaszero,//Output null string serializerfeature.writenullstringasempty,     
    Format output Date Serializerfeature.writedateusedateformat}; /** * Serializes Java object JSON * @param obj requires JSON serialization of the Java Object * @return JSON string/private static string Tojsonstr 
  ing (Object obj) {return json.tojsonstring (obj, features); 
   /** * Returns JSON format data * @param response * @param the Java object to be returned * @param encoding returns the encoded format of the JSON string */public static void JSON (HttpServletResponse response, Object data, String encoding) {//Set encoding format Response.set 
    ContentType ("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 format data using the default encoding * @param response * @param data the Java object to be returned */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 JS 
  ONP (httpservletresponse response, Object data) {JSONP (response, callback, data, encoding); 
   /** * Returns JSONP data using the default encoding * @param response * @param callback JSONP callback function name * @param data Jsonp  */public static void Jsonp (HttpServletResponse response, String callback, Object data) {JSONP (response, Callback, 
  data, encoding); /** * Returns JSONP data * @param response * @param callback JSONP callback function name * @param data JSONP * @para  M encoding JSONP data encoding/public static void Jsonp (HttpServletResponse response, String callback, Object data, string 
    encoding) {StringBuffer SB = new StringBuffer (callback); 
    Sb.append ("("); 
    Sb.append (tojsonstring (data)); 
 
    Sb.append (");"); 
    Sets the 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; 
  The public static void Setencoding (String encoding) {responsejsonutils.encoding = encoding; 
  public static String Getcallback () {return callback; 
  The public static void Setcallback (String callback) {responsejsonutils.callback = callback; 

 } 
}
/** * Returns JSON data in Servlet/@WebServlet ("/json.do") public class Jsonservlet extends 
 
  HttpServlet {private static final long serialversionuid = 7500835936131982864L; /** * Returns JSON format data */protected void Service (HttpServletRequest request, httpservletresponse response) throws Ser 
     
    Vletexception, IOException {map<string, object> data = new hashmap<string, object> (); 
    Data.put ("Date", new Date ()); 
    Data.put ("email", "accountwcx@qq.com"); 
    Data.put ("Age", 30); 
    Data.put ("name", "Csdn"); 
     
    Data.put ("Array", new int[]{1,2,3,4}); 
  Responsejsonutils.json (response, data); } 
} 
/** * servlet returns JSONP format data */@WebServlet ("/jsonp.do") public class Jsonpservlet extends Htt 
 
  Pservlet {private static final long serialversionuid = -8343408864035108293l; The/** * Request sends the callback parameter as the callback function and uses the default callback function if the callback parameter is not sent/protected void service (HttpServletRequest request, HTT Pservletresponse response) throws Servletexception, IOException {//client-sent callback function String callback = Request.getpara 
     
    Meter ("callback"); 
     
    map<string, object> data = new hashmap<string, object> (); 
    Data.put ("Date", new Date ()); 
    Data.put ("email", "accountwcx@qq.com"); 
    Data.put ("Age", 30); 
    Data.put ("name", "Csdn"); 
     
    Data.put ("Array", new int[]{1,2,3,4});  if (callback = null | | callback.length () = 0) {//If the client does not send a callback function, then use the default callback function Responsejsonutils.jsonp (response, 
    data); 
    }else{//Using the client's callback function Responsejsonutils.jsonp (response, callback, data); } 
  } 
} 

/** * Returns JSON and JSONP in STRUTS2/public class Jsonaction extends Actionsupport {private static final long serialve 
   
  Rsionuid = 5391000845385666048L; 
   
  /** * JSONP callback function/private String callback; 
     
    /** * Returns JSON */public void json () {HttpServletResponse response = Servletactioncontext.getresponse (); 
     
    map<string, object> data = new hashmap<string, object> (); 
    Data.put ("Date", new Date ()); 
    Data.put ("email", "accountwcx@qq.com"); 
    Data.put ("Age", 30); 
    Data.put ("name", "Csdn"); 
     
    Data.put ("Array", new int[]{1,2,3,4}); 
  Responsejsonutils.json (response, data); /** * Returns JSONP */public void Jsonp () {HttpServletResponse response = Servletactioncontext.getresp 
     
    Onse (); 
     
    map<string, object> data = new hashmap<string, object> (); 
    Data.put ("Date", new Date ()); 
    Data.put ("email", "accountwcx@qq.com"); 
    Data.put ("Age", 30); Data.pUT ("name", "Csdn"); 
     
    Data.put ("Array", new int[]{1,2,3,4});  if (callback = null | | callback.length () = 0) {//If the client does not send a callback function, then use the default callback function Responsejsonutils.jsonp (response, 
    data); 
    }else{//Using 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 request * @param response */@RequestMapping ("/json.do") public void json (HTTPSERVL Etrequest request, HttpServletResponse response) {map<string, object> data = new hashmap<string, object> ( 
     
    ); 
    Data.put ("Date", new Date ()); 
    Data.put ("email", "accountwcx@qq.com"); 
    Data.put ("Age", 30); 
    Data.put ("name", "Csdn"); 
     
    Data.put ("Array", new int[]{1,2,3,4}); 
  Responsejsonutils.json (response, data); /** * Returns JSONP data * @param callback JSONP callback function * @param request * @param response/@Reques 
    Tmapping ("/jsonp.do") public void JSON (String callback, HttpServletRequest request, httpservletresponse response) { Map<string, object> DATA = new hashmap<string, object> (); 
    Data.put ("Date", new Date ()); 
    Data.put ("email", "accountwcx@qq.com"); 
    Data.put ("Age", 30); 
    Data.put ("name", "Csdn"); 
     
    Data.put ("Array", new int[]{1,2,3,4});  if (callback = null | | callback.length () = 0) {//If the client does not send a callback function, then use the default callback function Responsejsonutils.jsonp (response, 
    data); 
    }else{//Using the client's callback function Responsejsonutils.jsonp (response, callback, data); 
 } 
  } 
}

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.