java访问http并获得json数据解析json数据

                                                   java访问http并获得json数据解析json数据

需要fastjson-1.1.24.jar

此方法必须访问http请求,访问https需要httpclient

具体方法:

@RequestMapping("geturl.do")

   public void geturl(HttpServletResponseresponse){

     

      String url = "http://localhost:8080/Test/getUsers.do?id=1";

      //new一个stringbuffer

      StringBuffer json = new StringBuffer();

      try {

         //通过url获得连接

         URL u = new URL(url);

         URLConnection yc = u.openConnection();

         //读取返回的数据

         BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(),"UTF-8"));

         String inputline = null;

         while((inputline=in.readLine())!=null){

            json.append(inputline);

         }

         in.close();

      } catch (Exception e) {

         e.printStackTrace();

      }

      //获得jsonobject

      JSONObject jo = JSON.parseObject(json.toString());

      JSONObject jo2 = jo.getJSONObject("data");

      //获得json数组

      JSONArray ja = jo2.getJSONArray("users");

      JSONObject jo3 = null;

      Users user = null;

      for (int i = 0; i < ja.size(); i++) {

         jo3 = ja.getJSONObject(i);

         user = new Users();

         user.setId(jo3.getIntValue("id"));

         user.setUsername(jo3.getString("username"));

         user.setPassword(jo3.getString("password"));

         user.setAge(jo3.getIntValue("age"));

         user.setSex(jo3.getIntValue("sex"));

         System.out.println(user.getUsername());

      }

   }

猜你喜欢

转载自blog.csdn.net/qq_35298784/article/details/79081344