Foundation mattress
In Java, there are many libs about json, such as jackjson, fastjson, gson, etc. I have used them, but it still seems too heavy for programmers who only need to make the java object return a json string. Moreover, some functions are very customizable. For example, when a java object's attribute is empty, these components will not output. Therefore, when I loop through the list object on the page, I always have to judge whether this attribute is undefined, which makes me very dissatisfied. So I decided to take some time to study what was going on.
But after a close look for a morning, I found that both fastjson and gson were written in a very complicated way, and there were no relevant documents or comments, so I finally gave up. So I found a relatively simple Java package that returns json on www.json.com. This lib only needs 5 java classes to run, which is exactly what I want. It should be noted that the official JSONArray does not support direct conversion of javabeans. For example, things like List<User> cannot be converted. They must be converted into a format like List<Map> to convert, so I modified it. Official documents include:
Let me first introduce the basic usage.
Use the JSONObject class to handle basic java objects, and the usage is roughly as follows:
public void testMap(){ Map<String,Object> map = new HashMap<String,Object>(); map.put("name", "qiu"); map.put("password", "123"); map.put("address", "china"); User user = new User(); user.setUserName("qiuqiu"); user.setPassword("123456"); user.getTels().add("123444556677"); user.getTels().add("6893493458585"); map.put("user", user); JSONObject json = new JSONObject(map); System.out.println(json.toString()); } If it is a collection object, the JSONArray class is used, and the usage is 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("123444556677"); 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, we can see that the usage of this lib is quite simple. It does not require a new object like gson, and fastjson's API design is also somewhat unreasonable. In the second code above, there is a toString(2) that indicates the output by indenting two spaces in a new line.
The above only introduces the basic usage, but this is not what you want. What you want is how to return an empty string when the object property is empty, rather than returning nothing. Although there are only 5 classes, it took me two or three hours to find the place. There is a method called populateMap in JSONObject, and at the end there is a small piece of code:
Object result = method.invoke(bean, (Object[])null); if (result != null) { this.map.put(key, wrap(result)); }That is, when the get method is called and returned as null, this property is not output. Of course, it is very simple to change:
Object result = method.invoke(bean, (Object[])null); this.map.put(key, result==null?"":wrap(result));
This finally solved the problem I wanted to solve. Of course, this lib is officially brought by JSON and is written quite simply. It is more suitable for situations where there are only a few or dozens of data at a time, such as pagination display. If the amount of data transmitted at a time is relatively large, you can consider using fastjson, etc. But I personally think that for most occasions, the most necessary customization is. For example, if you occasionally find a certain component that cannot meet the needs, the component has no documentation or comments, and the code is difficult to understand, which is basically the same as not open source, so that it has no meaning.
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 returns JSON tool class* Tool class depends on 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[]{ //Output the value of Null in the Map SerializerFeature.WriteMapNullValue, //If the Boolean object is Null, the output is false SerializerFeature.WriteNullBooleanAsFalse, //If List is Null, the output is [] SerializerFeature.WriteNullListAsEmpty, //If Number is Null, the output is 0 SerializerFeature.WriteNullNumberAsZero, //Output Null string SerializerFeature.WriteNullStringAsEmpty, //Format the output date SerializerFeature.WriteDateUseDateFormat }; /** * Serialize Java object JSON* @param obj Java object that requires JSON serialization* @return JSON string*/ private static String toJSONString(Object obj){ return JSON.toJSONString(obj, features); } /** * Return JSON format data* @param response * @param data Java object to be returned* @param encoding Return the encoding format of the JSON string*/ public static void json(HttpServletResponse response, Object data, String encoding){ //Set the 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(); } } /** * Return JSON format data, using default encoding* @param response * @param data Java object to be returned*/ public static void json(HttpServletResponse response, Object data){ json(response, data, encoding); } /** * Return JSONP data, using default encoding and default callback functions* @param response * @param data JSONP data*/ public static void jsonp(HttpServletResponse response, Object data){ jsonp(response, callback, data, encoding); } /** * Return JSONP data, using the default encoding* @param response * @param callback JSONP callback function name* @param data JSONP data*/ public static void jsonp(HttpServletResponse response, String callback, Object data){ jsonp(response, callback, data, encoding); } /** * Return JSONP data* @param response * @param callback JSONP callback function name* @param data JSONP data* @param encoding JSONP data*/ 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(");"); // Set 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; } 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 serialVersionUID = 7500835936131982864L; /** * Return json format data*/ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Map<String, Object> data = new HashMap<String, Object>(); data.put("date", new Date()); data.put("email", "[email protected]"); 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 HttpServlet { private static final long serialVersionUID = -8343408864035108293L; /** * The request will send callback parameter as a callback function. If the callback parameter is not sent, the default callback function will be used*/ 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>(); data.put("date", new Date()); data.put("email", "[email protected]"); 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, use the default callback function ResponseJsonUtils.jsonp(response, data); }else{ //Use the client's callback function ResponseJsonUtils.jsonp(response, callback, data); } } } } /** * Return JSON and JSONP in Struts2 */ public class JsonAction extends ActionSupport { private static final long serialVersionUID = 5391000845385666048L; /** * JSONP callback function*/ private String callback; /** * Return JSON */ public void json(){ HttpServletResponse response = ServletActionContext.getResponse(); Map<String, Object> data = new HashMap<String, Object>(); data.put("date", new Date()); data.put("email", "[email protected]"); data.put("age", 30); data.put("name", "csdn"); data.put("array", new int[]{1,2,3,4}); ResponseJsonUtils.json(response, data); } /** * Return JSONP */ public void jsonp(){ HttpServletResponse response = ServletActionContext.getResponse(); Map<String, Object> data = new HashMap<String, Object>(); data.put("date", new Date()); data.put("email", "[email protected]"); 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, 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.steretype.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(HttpServletRequest request, HttpServletResponse response){ Map<String, Object> data = new HashMap<String, Object>(); data.put("date", new Date()); data.put("email", "[email protected]"); data.put("age", 30); data.put("name", "csdn"); data.put("array", new int[]{1,2,3,4}); ResponseJsonUtils.json(response, data); } /** * Return JSONP data* @param callback JSONP's 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>(); data.put("date", new Date()); data.put("email", "[email protected]"); 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, use the default callback function ResponseJsonUtils.jsonp(response, data); }else{ //Use the client's callback function ResponseJsonUtils.jsonp(response, callback, data); } } }