Are You Feeling any difficulity while writing Core-Java Programs. Send those to me Here.

Sunday 3 August 2014

Example Program to read the JSON data from HTTP request

Read some data present in JSON object by making a HTTP request.


Program:




import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

 public class Test
 {
    public Test() { }

    public static void main(String[] args) throws IOException
    {
            URL url;
            HttpURLConnection connection = null;
            InputStream is = null;
            JSONParser parser = new JSONParser();

            try
            {
                url = new URL("https://maps.googleapis.com/maps/api/geocode/json?address=Madhapur+Hyderabad");
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.connect();
                is = connection.getInputStream();
                BufferedReader theReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                Object obj = parser.parse(theReader);
                JSONObject jsonObject = (JSONObject) obj;
JSONArray msg = (JSONArray) jsonObject.get("results");
Iterator<JSONObject> iterator = msg.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next().get("formatted_address"));
}
            }
            catch (Exception e) {
                    e.printStackTrace();
            }
    }

 }

4 comments:

  1. very well explained for more visit kidsfront.com/competitive-exams.html

    ReplyDelete
  2. Learn and practice some important MCQ with answers on various categories useful for competitive exams
    http://www.gkindiaonline.com/

    ReplyDelete
  3. you can also refer some java programme in this site GK Questions

    ReplyDelete
  4. 1 year mba colleges in india

    Goodness, inconceivable blog format! To what extent have you been blogging for? you made blogging look simple. The general look of your site is magnificent, not to mention the substance!

    ReplyDelete