Simplest way to read json from a URL in java

后端 未结 11 1094
情书的邮戳
情书的邮戳 2020-11-22 04:15

This might be a dumb question but what is the simplest way to read and parse JSON from URL in Java?

In Groovy, it\

11条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 04:54

    The easiest way: Use gson, google's own goto json library. https://code.google.com/p/google-gson/

    Here is a sample. I'm going to this free geolocator website and parsing the json and displaying my zipcode. (just put this stuff in a main method to test it out)

        String sURL = "http://freegeoip.net/json/"; //just a string
    
        // Connect to the URL using java's native library
        URL url = new URL(sURL);
        URLConnection request = url.openConnection();
        request.connect();
    
        // Convert to a JSON object to print data
        JsonParser jp = new JsonParser(); //from gson
        JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element
        JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object. 
        String zipcode = rootobj.get("zip_code").getAsString(); //just grab the zipcode
    

提交回复
热议问题