实现api返回json数据并在调用api时处理json数据

    xiaoxiao2021-04-13  53

    json数据如下 "name": [ { "age": 25, "height": 160, "weight": 100, "email": "1946898935" }, { "age": 26, "height": 178, "weight": 140, "email": "1234567" } ], "address": [ { "addressname": "福州市" }, { "addressname": "厦门市" } ] }下面的代码是访问一个页面并同时调用一个api; @RequestMapping("/myapitest")//url映射地址 public ModelAndView apitest(){ /* *这是一个页面访问urlmapping * * */ // System.out.println(mysendGet("http://localhost:8080/weidaiTest/testapi","param=p")); String s = mysendGet("http://localhost:8080/weidaiTest/testapi","param=p");//通过mysendGet函数调用接口 JSONObject json = JSONObject.fromObject(s);//将字符串转化为json对象 JSONArray jary = json.getJSONArray("name");//去到name对应的数组 System.out.println(JSONObject.fromObject(jary.get(0)).get("email"));//数组内部的元素是对象,见上面的ison数据,对应到eamil的1946898935 ModelAndView mv = new ModelAndView("test");//要返回到浏览器的页面 return mv; }以下是调用接口的函数 public static String mysendGet(String url, String param) { String result = ""; BufferedReader in = null; try { String urlNameString = url + "?" + param; // System.out.println("请求地址是"+urlNameString); URL realUrl = new URL(urlNameString); // 打开和URL之间的连接 URLConnection connection = realUrl.openConnection(); // 设置通用的请求属性 // 建立实际的连接 connection.connect(); // 定义 BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader( connection.getInputStream())); String line; while ((line = in.readLine()) != null) { System.out.println(line); result+=line; } System.out.println("String在mysendget:"+result); System.out.println("JSONObject在mysendget:"+JSONObject.fromObject(result)); } catch (Exception e) { System.out.println("发送GET请求出现异常!" + e); e.printStackTrace(); } // 使用finally块来关闭输入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return JSONObject.fromObject(result).toString();//可以直接返回result } 下面是一个极其简易的接口,接口返回的是json格式的字符串 @RequestMapping(value="/testapi",method=RequestMethod.GET) @ResponseBody public String testapi(HttpServletRequest req,HttpServletResponse rpon){ /* *这是一个接口 * * */ // System.out.println("调用了接口testapi并且获取到了参数param="+req.getParameter("param")); String s = "{\"name\":[{\"age\":25,\"height\":160,\"weight\":100,\"email\":\"1946898935\"},{\"age\":26,\"height\":178,\"weight\":140,\"email\":\"1234567\"}],\"address\":[{\"addressname\":\"福州市\"},{\"addressname\":\"厦门市\"}]}"; //JSONObject json = JSONObject.fromObject(s); return s; }
    转载请注明原文地址: https://ju.6miu.com/read-668563.html

    最新回复(0)