寫一個json格式API,http請求接收json資料
目前比較流行的公開API 大多都是返回json格式字串。如何建立自己的基於http請求返回json資料的api?
如下:
返回JSON字串的API
相關包:fastjson-1.2.2.jar
方式(一)基於SpringMVC
控制層Action程式碼:
@RequestMapping("/getJsonTest")
@ResponseBodypublic String getJsonTest(HttpServletRequest request,
HttpServletResponse response) throws IOException {
JSONObject result = new JSONObject();
if(StringUtils.isBlank(request.getParameter("phone"))){
result.put("status", "0");
result.put("msg", "phone欄位不能為空");
}else{
result.put("status", "1");
JSONObject oneJsonObject= new JSONObject();
oneJsonObject.put("myMap1", "一個map");
oneJsonObject.put("myMap2", "一個map");
result.put("oneMap",oneJsonObject );
onearray.add(0, "一個llist第一條");
onearray.add(1, "第二條");
result.put("oneList", onearray );
result.put("msg", "測試");
}
return result.toJSONString();//返回的是一個json字串
}
(二)直接用Selvlet 來實現:
public class JsonTestServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
JSONObject result = new JSONObject();
response.setContentType("text/html;charset=utf-8");
if(StringUtils.isBlank(request.getParameter("phone"))){
result.put("status", "0");
result.put("msg", "phone欄位不能為空");
}else{
result.put("status", "1");
JSONArray onearray= new JSONArray();
JSONObject oneJsonObject= new JSONObject();
oneJsonObject.put("myMap1", "一個map");
oneJsonObject.put("myMap2", "一個map");
result.put("oneMap",oneJsonObject );
onearray.add(0, "一個llist第一條");
onearray.add(1, "第二條");
result.put("oneList", onearray );
result.put("msg", "測試");
}
response.getWriter().print(result.toJSONString());
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
網頁開啟:http://localhost:8081/XXX/getJsonTest
顯示{"msg":"phone欄位不能為空","status":"0"}
http://datachina.win/app1.5/appTestServlet?phone=15514390110
顯示:
{"msg":"測試","oneList":["一個llist第一條","第二條"],"oneMap":{"myMap1":"一個map","myMap2":"一個map"},"status":"1"}
接收解析json資料
包:fastjson.
public static void main(String[] args) throws Exception {
Object result=esayGet("http://datachina.win/app1.5/appTestServlet?phone=15514390110", "utf-8");
System.out.println( result);
JSONObject object = JSONObject.parseObject(result.toString());
JSONArray array = JSONArray.parseArray(object.getString("oneList"));
JSONObject oneMap = JSONObject.parseObject(object.getString("oneMap"));
System.out.println(oneMap.get("myMap1"));
System.out.println(array.get(0));
}
{"msg":"測試","oneList":["一個llist第一條","第二條"],"oneMap":{"myMap1":"一個map","myMap2":"一個map"},"status":"1"}
一個map
一個llist第一條