2015-10-24 137 views
0

我正在使用黃頁API來訪問基於手機位置的商家信息。結果JSON返回和我解析這個成功:在Swift中訪問字典內的字典內的字典

do { 
     let searchResultsData = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary 

    print(searchResultsData) 
. 
. 
. 

的結果是包含其他字典和對象的混亂層次的字典。

這裏是主詞典內容的控制檯打印:

{ 
    searchResult =  { 
     metaProperties =   { 
      didYouMean = ""; 
      errorCode = ""; 
      inputParams =    { 
       "@xsi.type" = searchRequest; 
       appId = xxxxxxxx; 
       dnt = ""; 
       format = json; 
       listingCount = 2; 
       phoneSearch = 0; 
       radius = 5; 
       requestId = "a75efeb9-de0a-4411-8ee9-c6c43f3867e8"; 
       searchLocation = "37.33233141:-122.0312186"; 
       shortUrl = 0; 
       sort = distance; 
       term = pizza; 
       termType = ""; 
       test = ""; 
       userAgent = "Determine%20use%20location/1 CFNetwork/758.1.6 Darwin/14.5.0"; 
       userIpAddress = "22.1.2.33"; 
       userReferrer = internalReferrer; 
       visitorId = xxxxxxxxxx; 
      }; 
      listingCount = 2; 
      message = ""; 
      relatedCategories =    { 
       "@xsi.type" = rServiceFacets; 
       relatedCategory =     (
             { 
         count = 121; 
         name = Pizza; 
        }, 
             { 
         count = 105; 
         name = Restaurants; 
        }, 
             { 
         count = 78; 
         name = "Take Out Restaurants"; 
        }, 
             { 
         count = 41; 
         name = "Italian Restaurants"; 
        }, 
             { 
         count = 30; 
         name = Caterers; 
        } 
       ); 
      }; 
      requestId = "a75efeb9-de0a-4411-8ee9-c6c43f3867e8"; 
      resultCode = Success; 
      searchCity = Cupertino; 
      searchLat = "37.323056"; 
      searchLon = "-122.031111"; 
      searchState = CA; 
      searchType = Category; 
      searchZip = 95015; 
      totalAvailable = 121; 
      trackingRequestURL = "http://c.ypcdn.com/2/i/rtd?vrid=gpnx7mtbzw&rid=a75efeb9-de0a-4411-8ee9-c6c43f3867e8&ptid=gpnx7mtbzw&lsrc=MDM&cp=__"; 
      ypcAttribution = ""; 
     }; 
     searchListings =   { 
      searchListing =    (
           { 
        adImage = ""; 
        adImageClick = ""; 
        additionalText = " "; 
        audioURL = ""; 
        averageRating = "2.86"; 
        baseClickURL = "http://c.ypcdn.com/2/c/rtd?vrid=gpnx7mtbzw&rid=a75efeb9-de0a-4411-8ee9-c6c43f3867e8&ptid=gpnx7mtbzw&ypid=17510978&lid=17510978&lsrc=MDM"; 
        businessName = "BJ's Restaurants"; 
        businessNameURL = "http://c.ypcdn.com/2/c/rtd?vrid=gpnx7mtbzw&rid=a75efeb9-de0a-4411-8ee9-c6c43f3867e8&ptid=gpnx7mtbzw&ypid=17510978&lid=17510978&tl=1600&lsrc=MDM&dest=http%3A%2F%2Fwww.yellowpages.com%2Fcupertino-ca%2Fmip%2Fbjs-restaurants-17510978%3Ffrom%3Dpubapi_gpnx7mtbzw"; 
        categories = " Restaurants|Take Out Restaurants|Brew Pubs|American Restaurants|Pizza|Family Style Restaurants|Beer & Ale|"; 
        city = Cupertino; 
        claimed = 0; 
        claimedStatus = 0; 
        // removed for space 
       }, 
           { 
        // removed for space 
        // second listing follows same structure 
       } 
      ); 
     }; 
    }; 
} 

我刪除了大部分首批上市的所有空間的目的,第二上市。上市結構是一致的。返回列表的數量可以通過API參數進行控制。

正如您所見,主詞典中的第一項是另一個名爲searchResult的詞典。我可以通過以下方式成功訪問:

let dataReturned = searchResultsData["searchResult"]! 

但是,這是我卡住的地方。變量視圖顯示dataReturned屬於NSDictionary類型,但隨後顯示它包含和NSMutableDictionary,其中包含一個NSDictionary,它包含和NSObject,它包含或被命名爲NSDictionary類型的「isa」,帶有2個鍵值對,其中之一是我的鍵感興趣,命名爲searchListings。

我已經做了很多的搜索,並試圖向下鑽探進一步的方式,但不斷收到錯誤,而這一切基本上可以歸結爲暫時無法獲得過去dataReturned與鍵之間的對象:值我感興趣的

的如果您在此處看到屏幕截圖,問題會更有意義: http://screencast.com/t/VozRgLEzriD

我正在使用Xcode 7.1。任何有關如何深入到這種字典結構的建議將不勝感激。謝謝。

回答

0

你有問題,因爲你得到的詞典沒有告訴你任何關於它包含的內容。你將不得不這樣做:

if let 
    searchRes = searchResultsData["searchResult"] as? [NSObject : AnyObject], 
    listings = searchRes["searchListings"] as? [NSObject : AnyObject], 
    .... { 
     // here is your code 
} 

但這真的很麻煩。有一個很好的選擇:SwiftyJSON。它能夠像這樣(從SwiftyJSON所採取的示例)模式:

let json = JSON(data: data) 
if let userName = json[0]["user"]["name"].string { 
    //Now you got your value 
} 

JSON數據對象仍然不會告訴你它包含什麼,但至少你不需要檢查每一個時間。

+0

我有在我嘗試解決這個問題時遇到了SwiftyJSON的提及。我會再看看這個,謝謝你的迴應。 –

0

我創建了這個在線實用程序(http://www.json4swift.com),它將您的json轉換爲可以輕鬆地深入到結構中的swift可表示模型。所有你需要做的是粘貼您的JSON和生成的模型複製到您的項目,然後用它是這樣的:

//Create instance for base model representation 
    let responseModel = Json4Swift_Base(dictionary: searchResultsData) 

然後你的反應模型成爲你的字典的基於對象的表示

+0

如何從模型類訪問數據 – user2702179