需要帮助使用 Alamofire 使用 Swift 解析 JSON

Posted

技术标签:

【中文标题】需要帮助使用 Alamofire 使用 Swift 解析 JSON【英文标题】:Need Help Parsing JSON with Swift using Alamofire 【发布时间】:2016-02-17 03:08:53 【问题描述】:

我正在尝试从 Google 新闻中检索一篇文章并使用 Swift 对其进行解析。我正在使用 Alamofire。我知道解析时要做什么的基础知识,但输出似乎有点复杂,我不知道如何访问“标题”值。任何帮助,将不胜感激。谢谢!

这是 JSON 输出:


responseData =     
        cursor =         
            currentPageIndex = 0;
            estimatedResultCount = 445755633;
            moreResultsUrl = "http://news.google.com/nwshp?oe=utf8&ie=utf8&source=uds&q=sports&hl=en&start=0";
            pages =             (
                                
                    label = 1;
                    start = 0;
                ,
                                
                    label = 2;
                    start = 1;
                ,
                                
                    label = 3;
                    start = 2;
                ,
                                
                    label = 4;
                    start = 3;
                ,
                                
                    label = 5;
                    start = 4;
                ,
                                
                    label = 6;
                    start = 5;
                ,
                                
                    label = 7;
                    start = 6;
                ,
                                
                    label = 8;
                    start = 7;
                
            );
        ;
        results =         (
                        
                GsearchResultClass = GnewsSearch;
                clusterUrl = "http://news.google.com/news/story?ncl=dO-ivvqeXteuGKMAkRap55WyAkOvM&hl=en&ned=us";
                content = "sportsbook The Third Circuit Court of Appeals will rehear a potentially landmark case Wednesday brought by the NCAA, NFL, MLB, NBA and NHL claiming a New Jersey gambling law enacted in 2014 that repealed certain prohibitions on sports wagering in ...";
                image =                 
                    originalContextUrl = "http://lawnewz.com/sports/new-jersey-lawsuit-could-make-sports-betting-legal-across-the-country/";
                    publisher = LawNewz;
                    tbHeight = 53;
                    tbUrl = "http://t0.gstatic.com/images?q=tbn:ANd9GcQ2htg8w11Y6_4ClDD80jdQN6VtGGMya5KomCyLCgzVjOsyMJLVdkffcSg9";
                    tbWidth = 80;
                    url = "http://lawnewz.com/wp-content/uploads/2016/02/800px-Las_Vegas_sportsbook-351x234.jpg";
                ;
                language = en;
                location = "";
                publishedDate = "Tue, 16 Feb 2016 10:47:00 -0800";
                publisher = LawNewz;
                relatedStories =                 (
                                        
                        language = en;
                        location = "";
                        publishedDate = "Tue, 16 Feb 2016 07:34:35 -0800";
                        publisher = ESPN;
                        signedRedirectUrl = "http://news.google.com/news/url?sa=T&ct2=us&fd=S&url=http://espn.go.com/chalk/story/_/id/14785562/chalk-previewing-latest-new-jersey-sports-betting-appeal&cid=52779048299261&ei=5OHDVujuMfOmwQHOn53oAg&usg=AFQjCNH7bfL6cWr1Q8PKgPOkQIP7ZRUoRw";
                        title = "Future of sports betting once again at stake in New Jersey";
                        titleNoFormatting = "Future of sports betting once again at stake in New Jersey";
                        unescapedUrl = "http://espn.go.com/chalk/story/_/id/14785562/chalk-previewing-latest-new-jersey-sports-betting-appeal";
                        url = "http%3A%2F%2Fespn.go.com%2Fchalk%2Fstory%2F_%2Fid%2F14785562%2Fchalk-previewing-latest-new-jersey-sports-betting-appeal";
                    
                );
                signedRedirectUrl = "http://news.google.com/news/url?sa=T&ct2=us&fd=S&url=http://lawnewz.com/sports/new-jersey-lawsuit-could-make-sports-betting-legal-across-the-country/&cid=52779048299261&ei=5OHDVujuMfOmwQHOn53oAg&usg=AFQjCNHAqRF8uPjG1Ki7yxjz0sATv05i6A";
                title = "New Jersey Lawsuit Could Make Sports Betting Legal Across the Country";
                titleNoFormatting = "New Jersey Lawsuit Could Make Sports Betting Legal Across the Country";
                unescapedUrl = "http://lawnewz.com/sports/new-jersey-lawsuit-could-make-sports-betting-legal-across-the-country/";
                url = "http%3A%2F%2Flawnewz.com%2Fsports%2Fnew-jersey-lawsuit-could-make-sports-betting-legal-across-the-country%2F";
            
        );
    ;
    responseDetails = "";
    responseStatus = 200;

我对此感到非常困惑,因为它看起来不像我在网上看到的大多数示例。

【问题讨论】:

results 解析为自定义对象。尽可能少地将数据保存为 JSON。 【参考方案1】:

从 github 添加 SwiftyJSON 并执行以下操作

     import SwiftyJSON

      func parseJson() 

        Alamofire.request(.POST, "urlString", parameters:   parameter, encoding: .JSON)
        .responseJSON  response in


            //Check Response

            if response.result.isFailure == true 
                return
            

            let json = JSON(response.result.value!)

          let cursorEntity = json["Cursor"]
          let currentIndex = json["cursor"].currentPageIndex
          let pageEntity =  json["cursor"]["pages"]
          let resultsEntity = json["cursor"]["results"]
       
    

【讨论】:

谢谢!我又玩了一些,最后得到了 SwiftJSON 并使用了你的方法。现在效果很好!【参考方案2】:

将 Alamofire 与名为 Alamofire-SwiftyJSON 的 SwiftyJSON 插件一起使用

Alamofire.request(.GET, 
  urlString, 
  parameters: ["foo": "bar"])
.responseSwiftyJSON( (request, response, json, error) in
  var cursor = json["cursor"]
  // do your stuff ..
)

【讨论】:

【参考方案3】:

正如上面提到的@cem olcay,使用 Alamofire 和 SwiftyJSON。试试下面的代码。但尚未测试。

func getData() 
Alamofire.request(.GET, "YOUR_URL_STRING")
         .responseJSON  response in


let json = JSON(data: response)
if let title = json[0]["relatedStories"][0]["title"].string 
  //Now you got your value


         

【讨论】:

以上是关于需要帮助使用 Alamofire 使用 Swift 解析 JSON的主要内容,如果未能解决你的问题,请参考以下文章

Swift 3 - 不能使用数组提出的 Alamofire 请求

在 swift 4.0 中使用 Alamofire/SwiftyJSON 时出错

使用 Alamofire 在 Swift 中发布嵌套 JSON

如何使用 Alamofire 在 Swift 3 中解析 JSON?

如何在 Swift 4 中使用 Alamofire 上传具有其他参数的多个图像

使用 swift 4 和 Alamofire 在 UITableView 中显示 JSON 数据 [关闭]