First download json-lib and add it to your classpath. You'll also have to add following libraries to your classpath
- commons-lang.jar
- commons-beanutils.jar
- commons-collections.jar
- commons-logging.jar
- ezmorph.jar
What you need next is a request url and it's response should be JSON data. You will see mine in the example code I've provided, if you know how to use firebug the task will be much more simpler. In your browser run that request you'll get the JSON data which I parse, it's lengthy that's why I didn't add it in here. If you get untidy JSON data, format it using jasonlint.
Now let's move on to the example code, it's not hard to understand, simply go through it. Refer comments for clarifications.
java code
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import net.sf.json.JSONSerializer; public class JsonParse { public static void main(String[] args) { String jsonString = ""; String city = "London"; String country = "United+Kingdom"; //This is the request url String requestUrl = "http://www.bing.com/travel/hotel/hotelReferenceData.do?q=" + city + "%2C+" + country + "+leave+07%2F08%2F2011+return+07%2F10%2F2011+adults%3A2+rooms%3A1&distanceFrom=22&HotelPriceRange=1%2C2%2C3%2C4&pageOffset=0&pageCount=240&cim=2011-07-08&com=2011-07-10&a=2&c=0&r=1&sortBy=PopularityDesc"; try { URL url = new URL(requestUrl.toString()); BufferedReader in = new BufferedReader(new InputStreamReader( url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { //JSON data get stored as a string jsonString = inputLine; } in.close(); //the way to parse JSON array JSONArray json = (JSONArray) JSONSerializer.toJSON(jsonString); //getting another JSON string to parse String parse1 = json.getString(0); //the way to parse JSON object JSONObject json2 = (JSONObject) JSONSerializer.toJSON(parse1); //getting a json array inside JSON object JSONArray array1 = json2.getJSONArray("hotels"); for (int i = 0; i < array1.size(); i++) { //getting a JSON object inside JSON array JSONObject jhotelrec = array1.getJSONObject(i); System.out.println("Hotel Name= "+jhotelrec.getString("name")+"\n"+"Geo Codes= "+jhotelrec.getJSONArray("geoPoint").getString(0)+","+jhotelrec.getJSONArray("geoPoint").getString(1)); } } catch (IOException e) { e.printStackTrace(); } } }
For easier and faster Json parsing use Jackson: http://jackson.codehaus.org/
ReplyDeleteI prefer Jackson library : http://wiki.fasterxml.com/JacksonInFiveMinutes
ReplyDelete