Debug School

rakesh kumar
rakesh kumar

Posted on

Retrieving values from nested JSON Object

retrieving-values-from-nested-json-object
getting-data-from-a-deeply-nested-json-object

Problem

I've got JSON file, which I want to parse. The JSON file ("myfile") has format as follows:

{
    "LanguageLevels": {
        "1": "Początkujący",
        "2": "ŚrednioZaawansowany",
        "3": "Zaawansowany",
        "4": "Ekspert"
    }
}
Enter fullscreen mode Exit fullscreen mode

======================OR================

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Bhopal",
               "short_name" : "Bhopal",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Bhopal",
               "short_name" : "Bhopal",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Madhya Pradesh",
               "short_name" : "MP",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "India",
               "short_name" : "IN",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "Bhopal, Madhya Pradesh, India",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 23.3326697,
                  "lng" : 77.5748062
               },
               "southwest" : {
                  "lat" : 23.0661497,
                  "lng" : 77.2369767
               }
            },
            "location" : {
               "lat" : 23.2599333,
               "lng" : 77.412615
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 23.3326697,
                  "lng" : 77.5748062
               },
               "southwest" : {
                  "lat" : 23.0661497,
                  "lng" : 77.2369767
               }
            }
         },
         "place_id" : "ChIJvY_Wj49CfDkR-NRy1RZXFQI",
         "types" : [ "locality", "political" ]
      }
   ],
   "status" : "OK"
}
Enter fullscreen mode Exit fullscreen mode

Solution

 JSONObject json = new JSONObject(output.toString());
        JSONArray result = json.getJSONArray("results");
        JSONObject result1 = result.getJSONObject(0);
        JSONObject geometry = result1.getJSONObject("geometry");
        JSONObject locat = geometry.getJSONObject("location");

        //"iterate onto level of location";

        double lat = locat.getDouble("lat");
        double lng = locat.getDouble("lng");
Enter fullscreen mode Exit fullscreen mode
JSONObject jsonChildObject = (JSONObject)jsonObject.get("LanguageLevels");
for (Map.Entry in jsonChildOBject.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
Enter fullscreen mode Exit fullscreen mode
JSONArray jsonChildArray = (JSONArray) jsonChildArray.get("LanguageLevels");
    JSONObject secObject = (JSONObject) jsonChildArray.get(1);
Enter fullscreen mode Exit fullscreen mode

Getting data from a deeply nested json object

{ "HotelListResponse" : { "HotelList" : { "@activePropertyCount" : "168",
          "@size" : "2",
          "HotelSummary" : [ { "@order" : "0",
                "@ubsScore" : "360017",
                "RoomRateDetailsList" : { "RoomRateDetails" : { "RateInfos" : { "@size" : "1",
                            "RateInfo" : { "@priceBreakdown" : "true",
                                "@promo" : "true",
                                "@rateChange" : "true",
                                "ChargeableRateInfo" : { "@averageBaseRate" : "68.62333",
                                    "@averageRate" : "68.62333",
                                    "@commissionableUsdTotal" : "205.87",
                                    "@currencyCode" : "USD",
                                    "@grossProfitOffline" : "14.06",
                                    "@grossProfitOnline" : "27.44",
                                    "@maxNightlyRate" : "77.87",
                                    "@nightlyRateTotal" : "205.87",
                                    "@total" : "205.87",
                                    "NightlyRatesPerRoom" : { "@size" : "3",
                                        "NightlyRate" : [ { "@baseRate" : "77.87",
                                              "@promo" : "false",
                                              "@rate" : "77.87"
                                            },
                                            { "@baseRate" : "64.0",
                                              "@promo" : "false",
                                              "@rate" : "64.0"
                                            },
                                            { "@baseRate" : "64.0",
                                              "@promo" : "false",
                                              "@rate" : "64.0"
                                            }
                                          ]
                                      }
                                  },
                                "RoomGroup" : { "Room" : { "numberOfAdults" : 2,
                                        "numberOfChildren" : 0,
                                        "rateKey" : "f82ab843-49ee-481a-b53a-71647592b183"
                                      } },
                                "currentAllotment" : 0,
                                "nonRefundable" : true,
                                "promoDescription" : "Advance Purchase Special - non-refundable",
                                "promoId" : 200827770,
                                "promoType" : "Standard",
                                "rateType" : "MerchantStandard"
                              }
                          },
                        "ValueAdds" : { "@size" : "1",
                            "ValueAdd" : { "@id" : "2048",
                                "description" : "Free Wireless Internet"
                              }
                          },
                        "expediaPropertyId" : 3084588,
                        "maxRoomOccupancy" : 3,
                        "minGuestAge" : 0,
                        "propertyAvailable" : true,
                        "propertyRestricted" : false,
                        "quotedRoomOccupancy" : 2,
                        "rateCode" : 200371945,
                        "roomDescription" : "Standard Room with King size bed",
                        "roomTypeCode" : 477014
                      } },
                "address1" : "Stone Cellar Road",
                "address2" : "High Usworth Newcastle",
                "airportCode" : " ",
                "amenityMask" : 18063491,
                "city" : "Washington",
                "confidenceRating" : 90,
                "countryCode" : "GB",
                "deepLink" : "http://travel.ian.com/index.jsp?pageName=hotAvail&cid=55505&hotelID=340461&mode=2&numberOfRooms=1&room-0-adult-total=2&room-0-child-total=0&arrivalMonth=11&arrivalDay=12&departureMonth=11&departureDay=15&showInfo=true&locale=en_US&currencyCode=USD",
                "highRate" : 77.870000000000005,
                "hotelId" : 340461,
                "hotelInDestination" : true,
                "hotelRating" : 3,
                "latitude" : 54.922739999999997,
                "locationDescription" : "Near Washington Old Hall",
                "longitude" : -1.5342899999999999,
                "lowRate" : 64,
                "name" : "Mercure Newcastle George Washington Hotel Golf and Spa",
                "postalCode" : "NE37 1PH",
                "propertyCategory" : 1,
                "proximityDistance" : 1.4710813,
                "proximityUnit" : "MI",
                "rateCurrencyCode" : "USD",
                "shortDescription" : "<p><b>Location. </b> <br />Mercure Newcastle George Washington Hotel Golf and Spa is a business-friendly hotel located in Washington, close to Washington Old Hall, Angel of the North, and WWT",
                "supplierType" : "E",
                "thumbNailUrl" : "/hotels/4000000/3090000/3084600/3084588/3084588_84_t.jpg",
                "tripAdvisorRating" : 3.5,
                "tripAdvisorRatingUrl" : "http://www.tripadvisor.com/img/cdsi/img2/ratings/traveler/3.5-12345-4.gif",
                "tripAdvisorReviewCount" : 215
              },
              { "@order" : "1",
                "@ubsScore" : "258461",
                "RoomRateDetailsList" : { "RoomRateDetails" : { "RateInfos" : { "@size" : "1",
                            "RateInfo" : { "@priceBreakdown" : "true",
                                "@promo" : "false",
                                "@rateChange" : "true",
                                "ChargeableRateInfo" : { "@averageBaseRate" : "54.83667",
                                    "@averageRate" : "54.83667",
                                    "@commissionableUsdTotal" : "164.51001",
                                    "@currencyCode" : "USD",
                                    "@grossProfitOffline" : "11.69",
                                    "@grossProfitOnline" : "22.38",
                                    "@maxNightlyRate" : "63.47",
                                    "@nightlyRateTotal" : "164.51001",
                                    "@total" : "164.51",
                                    "NightlyRatesPerRoom" : { "@size" : "3",
                                        "NightlyRate" : [ { "@baseRate" : "50.52",
                                              "@promo" : "false",
                                              "@rate" : "50.52"
                                            },
                                            { "@baseRate" : "50.52",
                                              "@promo" : "false",
                                              "@rate" : "50.52"
                                            },
                                            { "@baseRate" : "63.47",
                                              "@promo" : "false",
                                              "@rate" : "63.47"
                                            }
                                          ]
                                      }
                                  },
                                "RoomGroup" : { "Room" : { "numberOfAdults" : 2,
                                        "numberOfChildren" : 0,
                                        "rateKey" : "f82ab843-49ee-481a-b53a-71647592b183"
                                      } },
                                "currentAllotment" : 0,
                                "nonRefundable" : true,
                                "rateType" : "MerchantStandard"
                              }
                          },
                        "expediaPropertyId" : 901118,
                        "maxRoomOccupancy" : 2,
                        "minGuestAge" : 0,
                        "propertyAvailable" : true,
                        "propertyRestricted" : false,
                        "quotedRoomOccupancy" : 2,
                        "rateCode" : 200369466,
                        "roomDescription" : "Standard room with double bed - Book early & Save",
                        "roomTypeCode" : 162976
                      } },
                "address1" : "Emerson Road",
                "address2" : "District 5",
                "airportCode" : "NCL",
                "amenityMask" : 1507328,
                "city" : "Washington",
                "confidenceRating" : 85,
                "countryCode" : "GB",
                "deepLink" : "http://travel.ian.com/index.jsp?pageName=hotAvail&cid=55505&hotelID=207631&mode=2&numberOfRooms=1&room-0-adult-total=2&room-0-child-total=0&arrivalMonth=11&arrivalDay=12&departureMonth=11&departureDay=15&showInfo=true&locale=en_US&currencyCode=USD",
                "highRate" : 63.469999999999999,
                "hotelId" : 207631,
                "hotelInDestination" : true,
                "hotelRating" : 2,
                "latitude" : 54.895090000000003,
                "locationDescription" : "Near Washington Old Hall",
                "longitude" : -1.55661,
                "lowRate" : 50.520000000000003,
                "name" : "Campanile Washington Newcastle Upon Tyne",
                "postalCode" : "NE37 1LB",
                "propertyCategory" : 1,
                "proximityDistance" : 1.2526573000000001,
                "proximityUnit" : "MI",
                "rateCurrencyCode" : "USD",
                "shortDescription" : "<p><b>Location. </b> <br />Campanile Washington Newcastle Upon Tyne is located in Washington, close to Washington Old Hall, Angel of the North, and WWT Washington Wetland Centre. Additional area",
                "supplierType" : "E",
                "thumbNailUrl" : "/hotels/1000000/910000/901200/901118/901118_20_t.jpg",
                "tripAdvisorRating" : 3.5,
                "tripAdvisorRatingUrl" : "http://www.tripadvisor.com/img/cdsi/img2/ratings/traveler/3.5-12345-4.gif",
                "tripAdvisorReviewCount" : 55
              }
            ]
        },
      "cacheKey" : "4ef59f3e:13e1c495694:-6e28",
      "cacheLocation" : "10.186.168.74:7301",
      "cachedSupplierResponse" : { "@cachedTime" : "0",
          "@candidatePreptime" : "100",
          "@matchedCurrency" : "true",
          "@matchedLocale" : "true",
          "@otherOverheadTime" : "3",
          "@supplierCacheTolerance" : "MED",
          "@supplierRequestNum" : "118",
          "@supplierResponseNum" : "2",
          "@supplierResponseTime" : "468",
          "@tpidUsed" : "5200"
        },
      "customerSessionId" : "0ABAA84A-59F3-E913-E1C2-495694906E33",
      "moreResultsAvailable" : true,
      "numberOfRoomsRequested" : 1
    } } 

Enter fullscreen mode Exit fullscreen mode
var rateInfo = json["HotelListResponse"]["HotelList"]["HotelSummary"][0]["RoomRateDetailsList"]["RoomRateDetails"]["RateInfos"]["RateInfo"];

var result =JsonConvert.DeserializeObject<RateInfo>( rateInfo .ToString() );
Enter fullscreen mode Exit fullscreen mode
IList<JToken> rates = root["HotelListResponse"]["HotelList"]["HotelSummary"][0]["RoomRateDetailsList"]["RoomRateDetails"]["RateInfos"].Children().ToList();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)