JSON, Servlet, JSP

十年热恋 提交于 2020-01-05 02:28:13

问题


Firstly, my HTTP POST through a URL accepts 4 parameters. (Param1, Param2, Param3, Param4).

Can I pass the parameters from the database?

Once the URL is entered, the information returned will be in text format using JSON format.

The JSON will return either {"Status" : "Yes"} or {"Status" : "No"}

How shall I do this in servlets? doPost()


回答1:


Just set the proper content type and encoding and write the JSON string to the response accordingly.

String json = "{\"status\": \"Yes\"}";
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);

Instead of composing the JSON yourself, you may consider using an existing JSON library to ease the job of JSON (de)serializing in Java. For example Google Gson.

Map<String, String> result = new HashMap<String, String>();
result.put("status", "Yes");
// ... (put more if necessary)

String json = new Gson().toJson(result);
// ... (just write to response as above)



回答2:


Jackson is another option for JSON object marshalling.



来源:https://stackoverflow.com/questions/4020311/json-servlet-jsp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!