目前比较流行的公开API 大多都是返回json格式字符串。如何创建自己的基于http请求返回json数据的api?
如下:
返回JSON字符串的API
相关包:fastjson-1.2.2.jar
方式(一)基于SpringMVC
控制层Action代码:
@RequestMapping("/getJsonTest")
@ResponseBody
public 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");
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", "测试");
}
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第一条