如何在Swift中使用多个数组解析JSON

时间:2016-08-08 10:22:22

标签: ios arrays json swift swift2

我是快速语言,新手问题的新手,但我不得不问,因为我对这里的字典和数组使用有点困惑,我得到了像这样的json;

 {
  "MainPageLast": [
  {},
  {}..
  ],
  "MainPageSport": [
  {},
  {}..
  ],
  "MainPageEco": [
  {},
  {}..
  ],
  "MainPagePol": [
  {},
  {}..
  ]
}

我创建了基类,其中包含所有这些数组作为这样的字典;

public class func modelsFromDictionaryArray(array:NSArray) -> [Json4Swift_Base]
    {
        var models:[Json4Swift_Base] = []
        for item in array
        {
            models.append(Json4Swift_Base(dictionary: item as! NSDictionary)!)
        }
        return models
    }

required public init?(dictionary: NSDictionary) {

        if (dictionary["MainPageLast"] != nil) { mainPageLast = MainPageLast.modelsFromDictionaryArray(dictionary["MainPageLast"] as! NSArray) }
        if (dictionary["MainPageSport"] != nil) { mainPageSport = MainPageSport.modelsFromDictionaryArray(dictionary["MainPageSport"] as! NSArray) }
        if (dictionary["MainPageEco"] != nil) { mainPageEco = MainPageEco.modelsFromDictionaryArray(dictionary["MainPageEco"] as! NSArray) }
        if (dictionary["MainPagePol"] != nil) { mainPagePol = MainPagePol.modelsFromDictionaryArray(dictionary["MainPagePol"] as! NSArray) }
    }

public func dictionaryRepresentation() -> NSDictionary {

        let dictionary = NSMutableDictionary()


        return dictionary
    }

我尝试获取数据并尝试解析并希望在调试屏幕中看到返回的数据;

func loadHeadline(completion : ((AnyObject) -> Void)!) {

        let urlString = "http://myapiurl."

        let session = NSURLSession.sharedSession()
        let newsUrl = NSURL(string: urlString)

        let task = session.dataTaskWithURL(newsUrl!, completionHandler: {
            (data, response, error) -> Void in

            do {
                let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! Dictionary<String, AnyObject>

                var models:[Json4Swift_Base] = []
                for item in jsonData
                {
                    models.append(Json4Swift_Base(dictionary: item as NSDictionary)!)
                }

            } catch let error as NSError{
                print("Failed to load: \(error.localizedDescription)")
            }

        })
        task.resume()
    }

我知道我需要在Json4Swift_Base课程中逐个到达每个[0],[1] ...项目,但我真的无法理解如何。

当我尝试

时抛出此异常
models.append

exc_bad_instruction (code=exc_i386_invop subcode=0x0)

现在,我应该采用哪种方式或将所有数据合并到一起。

感谢您的建议..

1 个答案:

答案 0 :(得分:2)

let jsonData = try NSData(contentsOfFile: path, options: NSDataReadingOptions.DataReadingMappedIfSafe)
                do {
                    let jsonResult = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers) as! NSArray

                    if let allData = jsonResult[0] as? NSDictionary {
                        let header = allData.objectForKey("MainPageMansetData")
                        let magazine = allData.objectForKey("MainPageMagazineData")
                        let sports = allData.objectForKey("MainPageSportsData")
                        let articles = allData.objectForKey("MainPageOtherArticles")

                        print("\(header) \n \(magazine) \n \(sports) \n \(articles)")
                    }
                } catch {}