【问题标题】:How to Parse JSON with more than one array in Swift如何在 Swift 中使用多个数组解析 JSON
【发布时间】:2016-12-14 01:59:06
【问题描述】:

我是 swift 语言的新手,新手问题,但我必须问一下,因为我对这里的字典和数组用法有点困惑,我得到了这样的 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)

现在,我应该遵循哪种方式或如何获取所有数据并将其放入一个中。

谢谢你的建议..

【问题讨论】:

  • 你有你要处理的 json 样本数据集吗?我可以在操场上试试
  • @Scriptable 请检查第一个代码块。您需要有关它的更多信息吗?谢谢。
  • 我认为知道数组中的内容会很方便
  • 由于您是 Swift 新手,因此请习惯原生集合类型 ArrayDictionary,它们比 Foundation 等价物更适合 Swift 的强类型系统。
  • @vadian 感谢您的建议,但我需要弄清楚如何处理..

标签: ios arrays json swift swift2


【解决方案1】:
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 {}

【讨论】:

  • 你能检查更新的代码块吗?在 Json4Swift_Base 中,最后也有类似的代码块。所以它是字典。我也试过你的答案,xcode说; “不能强制将值类型任何对象转换为 nsdictionary..”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-29
  • 1970-01-01
  • 2014-07-24
  • 1970-01-01
  • 2017-06-24
  • 1970-01-01
相关资源
最近更新 更多