4

I am a newbie to json parsing, I have grabbed a json string from a request and now I need to parse it with java. I'm using json-lib for this. But I'm really stuck as I'm not familiar with it. I need to extract following data

1. name (hotel name)
2. starRating
3. geoPoint

I used following java code for that but it's not giving me the result I need, please someone help me...

Thanks a lot!

java code (s is the json string I get)

JSONObject json = (JSONObject) JSONSerializer.toJSON(s);    
JSONArray jarray = json.getJSONArray("hotels");
for(int i=0 ; i < jarray.size(); i++) {
System.out.println("jarray [" + i + "] --------" + jarray.getString(i));
}

json I need to parse

[
{
    "total": 250,
    "offset": 0,
    "requestID": "-btygi09oxfov",
    "locationName": "Paris, France",
    "locationLatitude": 48.86,
    "locationLongitude": 2.34,
    "cityCode": "PARIS_J_FR",
    "hotels": [
        {
            "ypid": "YN10001x300073304",
            "id": 56263,
            "hotelRateIndicator": "2",
            "name": "Renaissance Paris Vendome Hotel",
            "brandCode": "69",
            "addressLine1": "4 Rue du Mont-Thabor",
            "city": "Paris",
            "neighborhood": "",
            "state": "IdF",
            "country": "US",
            "cachedPrice": 935,
            "geoPoint": [
                48.865361,
                2.329584
            ],
            "starRating": "5",
            "thumbnailUrl": "http://www.orbitz.com//public/hotelthumbnails/53/97/85397/85397_TBNL_1246535840051.jpg",
            "total": 250,
            "amenities": [
                "24",
                "31",
                "42",
                "52",
                "9"
            ],
            "telephoneNumbers": [
                ""
            ],
            "popularity": 837
        },
        {
            "ypid": "YN10001x300073331",
            "id": 112341,
            "hotelRateIndicator": "3",
            "name": "Renaissance Paris Arc de Triomphe Hotel",
            "brandCode": "69",
            "addressLine1": "39 Avenue de Wagram",
            "city": "Paris",
            "neighborhood": "",
            "state": "IdF",
            "country": "US",
            "cachedPrice": 633,
            "geoPoint": [
                48.877107,
                2.297451
            ],
            "starRating": "5",
            "thumbnailUrl": "http://www.orbitz.com//public/hotelthumbnails/21/72/302172/302172_TBNL_1246535872514.jpg",
            "total": 250,
            "amenities": [
                "24",
                "31",
                "42",
                "9"
            ],
            "telephoneNumbers": [
                ""
            ],
            "popularity": 796
        }           
  ]         
}           
  ]
Programmer Bruce
  • 64,977
  • 7
  • 99
  • 97
Pavithra Gunasekara
  • 3,902
  • 8
  • 36
  • 46

5 Answers5

6

Any JSON object can be represented as a Map<String, Object>.

Use a library like jackson (shipped with spring), which can deserialize json to a Map like this:

Map<String, Object> obj = new ObjectMapper().readValue(json, new TypeReference<Map<String, Object>>());

Or the slower, but google-branded, GSON, which can be used like.

Map<String, Object> obj = new Gson().fromJson(json, HashMap.class);
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • 1
    Thanks for the suggestion but I'm in a situation where I must use json-lib :) – Pavithra Gunasekara Jul 01 '11 at 08:41
  • 1
    Gee - 2 downvotes? Honestly, gson can build java objects from json and visa versa so easily. Anyway... – Bohemian Jul 01 '11 at 09:30
  • I just did a benchmark of some of the most popular json libraries in java. I was shocked when i saw GSON is the least performing modern library (there are older and worse ones). Take a look for yourself if you don't believe me: https://github.com/fabienrenaud/java-json-benchmark I always assumed jackson and gson were similar in performance before... jackson is a clear winner in this pic tho. – fabien Jun 27 '16 at 20:39
  • @fab that's good, because long since I posted this answer I have been using jackson, not because it's faster, but because it comes out of the box with spring boot, which I have been using a lot in recent years. I've updated the answer to include jackson and a link to your benchmark. – Bohemian Jun 27 '16 at 21:37
5

To get past the ClassCastException, you just need to make the change it's telling you to make: to handle the input as an array and not as an object.

JSONArray outerArray = (JSONArray) JSONSerializer.toJSON(s);
JSONObject json = (JSONObject) outerArray.get(0);
JSONArray jarray = json.getJSONArray("hotels");
for (int i = 0; i < jarray.size(); i++)
{
  System.out.println("jarray [" + i + "] --------" + jarray.getString(i));
}

And, here's an example of getting each hotel name.

JSONArray outerArray = (JSONArray) JSONSerializer.toJSON(s);
JSONObject json = (JSONObject) outerArray.get(0);
JSONArray jarray = json.getJSONArray("hotels");
for (int i = 0; i < jarray.size(); i++)
{
  JSONObject hotel = jarray.getJSONObject(i);
  String name = hotel.getString("name");
  System.out.println(name);
}
Programmer Bruce
  • 64,977
  • 7
  • 99
  • 97
0

I recommend Djson parser(java library). https://github.com/jungkoo/djson_parser

code:

Var hotels = Djson.parse(new File("d:\\sample1.txt")).find("[0].hotels");

for(int i=0; i<hotels.size(); i++) {            
  System.out.println(hotels.get(i).get("name").toString());
  System.out.println(hotels.get(i).get("starRating").toInt());
  System.out.println(hotels.get(i).find("geoPoint").get(0).toDouble()); // case1) basic
  System.out.println(hotels.get(i).find("geoPoint[1]").toDouble()); // case2) find()    
  System.out.println();
}

output:

Renaissance Paris Vendome Hotel 5
48.865361
2.329584

Renaissance Paris Arc de Triomphe Hotel 5
48.877107
2.297451
tost
  • 7
  • 1
0

Download the json-lib and Use JSONObject

Lets say {"name": "joe", "age": 33}

Do like this

JSONObject jobject=new JSONObject(jsonstring);
String name=jobject.getString("name");
Fizer Khan
  • 88,237
  • 28
  • 143
  • 153
0

I have started a github project project called JsonQuery that makes this kind of thing easier.

The project is built on top of GSON.

If you wanted to retrieve the name of your hotel, for example, it could be as simple as this:

JsonQuery $ = JsonQuery.fromJson(s); 
$.val("hotels.name");

Here is the link:

https://github.com/rdbeach/JsonQuery