[swift]不解析 Json 解析在 iOS 操场 do 方法

标签: json ios Swift
发布时间: 2017/3/5 23:59:24
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我想一些 json 数据解析成三个不同的数组基于 json 中的标签。我似乎被卡住了,不知道为什么我的永远不会进入循环。我刚到 iOS,用这个来学习 swift 。任何帮助将不胜感激。 以下是我使用的代码︰

var myPicture = [String]()
var myPath = [String]()
var mylabel = [String]()


let jsonString = "[{\"picture\" : \"Picture 1 \", \"path\": \"Path 1\" , \"label\" : \"Label 1\"}]"
//Convert jsonString to NSData
let myData = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!

do{

let promoJson = try NSJSONSerialization.JSONObjectWithData(myData, options:.AllowFragments)

if let promtions = promoJson[""] as? [[String: AnyObject]] {

    for promtions in promtions {

        if let picture = promtions["picture"] as? String
        {
            myPicture.append(picture)

            if let path = promtions["path"] as? String
            {
                myPath.append(path)

                if let label = promtions["label"] as? String
                {
                    mylabel.append(label)

                }

            }
        }
    }

}

}catch {
print("Error with Json: \(error)")
}
print(myPicture.first)
print(myPath.first)
print(mylabel.first)

打印结果都为零。所以什么也不被追加到阵列

解决方法 1:

if let promtions = promoJson[""]部分不会工作,反正都是无用。这只是 promoJson ,你必须强制转换为数组的词典。

你还没那远未解决,看在我的工作版本的代码︰

do {
    let promoJson = try NSJSONSerialization.JSONObjectWithData(myData, options: [])
    if let promtions = promoJson as? [[String: AnyObject]] {
        for promtion in promtions {
            if let picture = promtion["picture"] as? String {
                myPicture.append(picture)
            }
            if let path = promtion["path"] as? String {
                myPath.append(path)
            }
            if let label = promtion["label"] as? String {
                mylabel.append(label)
            }
        }
    }
} catch let error as NSError {
    print(error.debugDescription)
}

替代

现在,问题已经解决,我建议你另一种方式︰ 而不是为您的数据的单独阵列,使用一个对象数组,保存您的数据。

例如,使象这样的结构︰

struct Promotion {
    let picture: String
    let path: String
    let label: String
}

数组为此结构的实例︰

var myPromotions = [Promotion]()

现在我们可以解码 JSON,从它创建对象,然后将它们存储在数组中︰

do {
    let promoJson = try NSJSONSerialization.JSONObjectWithData(myData, options: [])
    if let promtions = promoJson as? [[String: AnyObject]] {
        for promtion in promtions {
            if let picture = promtion["picture"] as? String,
                    path = promtion["path"] as? String,
                    label = promtion["label"] as? String {
                let promo = Promotion(picture: picture, path: path, label: label)
                myPromotions.append(promo)
            }
        }
    }
} catch let error as NSError {
    print(error.debugDescription)
}

现在看看数组,很方便的内容︰

for promo in myPromotions {
    print(promo.label)
    print(promo.path)
    print(promo.picture)
}
赞助商