在Swift

时间:2015-10-24 18:35:36

标签: ios json swift dictionary

我正在使用黄页API根据手机的位置访问商家信息。结果以JSON格式返回,我正在成功解析:

    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,其中包含或命名为'isa'的NSDictionary类型,带有2个键值对,其中一个是我的关键感兴趣的是,名为searchListings。

我已经进行了大量搜索并尝试了进一步向下钻取的方法,但仍然遇到错误,这些错误基本上归结为无法通过dataReturned和关键字之间的对象:我感兴趣的值。

如果你在这里看到屏幕截图,这个问题会更有意义: http://screencast.com/t/VozRgLEzriD

我正在使用Xcode 7.1。任何关于如何深入研究这个字典结构的建议将不胜感激。感谢。

2 个答案:

答案 0 :(得分:0)

你遇到了问题,因为你得到的词典没有告诉你它包含什么。你必须做这样的事情:

foo

但这真的很麻烦。有一个很好的选择:SwiftyJSON。它启用了这样的模式(例子来自SwiftyJSON):

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

json数据对象仍然没有告诉你它包含什么,但至少你不需要每次都检查。

答案 1 :(得分:0)

我创建了这个在线实用程序(http://www.json4swift.com),它可以将您的json转换为快速可表示的模型,您可以轻松地深入到结构中。您需要做的就是粘贴Json并将生成的模型复制到项目中,然后像这样使用它:

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

然后您的响应模型成为您的字典的基于对象的表示