简体   繁体   中英

return json format response

I have web service that use another web service. How can i get json format response and return json format again. Hear is my code : @Controller @RequestMapping("/idx") public class HomeController {

    @GetMapping("/{name}")
    public @ResponseBody List<String> idx(@PathVariable String name) {
        List<String> list = new ArrayList<String>(); 
         try {

                JSONParser parser = new JSONParser();
                URL url = new URL("https://api.openweathermap.org/data/2.5/weather?q="+name+"&APPID=7dc66995a09d2c3db6e");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setRequestProperty("Accept", "application/json");

                if (conn.getResponseCode() != 200) {
                    throw new RuntimeException("Failed : HTTP error code : "
                            + conn.getResponseCode());
                }
                BufferedReader br = new BufferedReader(new InputStreamReader(
                        (conn.getInputStream())));

                    String output;
                    System.out.println("Output from Server .... \n");
                    while ((output = br.readLine()) != null) {
                        System.out.println(output);
                        list.add(output);
                    }
                conn.disconnect();

              } catch (MalformedURLException e) {

                e.printStackTrace();

              } catch (IOException e) {

                e.printStackTrace();

              }
        return list;


    }

I see that you are using spring framework, I would recommend you to use restTemplate to consume rest APIs. You can get json response like below:

RestTemplate rest = new RestTemplate();
rest.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
JSONObject obj = rest.getForObject("https://api.openweathermap.org/data/2.5/weather?q=\"+name+\"&APPID=7dc66995a09d2c3db6e", JSONObject.class);

If you want to continue using HttpURLConnection there's an answer here that you can follow: Parse JSON from HttpURLConnection object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM