如何在SwiftyJSON中循环对象?不仅仅是快速的

时间:2017-03-15 01:59:13

标签: ios json swift swifty-json

var tempJSON:JSON = ""
tempJSON = JSON(self.userdefaults.string(forKey: "currentOrder"))
print(tempJSON)

的产率:

{"7": "1", "21": "0", "20": "0", "3": "1"}

我需要能够遍历这个并且不能。 我试过了。

for(key,value) in tempJSON{
       print(key)

            }

并且没有输出......

由于

4 个答案:

答案 0 :(得分:1)

尝试从字符串中获取Data并使用它来初始化JSON对象:

let jsonString = "{\"7\": \"1\", \"21\": \"0\", \"20\": \"0\", \"3\": \"1\"}"
if let dataFromString = jsonString.data(using: .utf8, allowLossyConversion: false) {
    let tempJSON = JSON(data: dataFromString)
    print(tempJSON)

    for (key, value) in tempJSON {
        print(key)
        print(value.stringValue)
    }
}

答案 1 :(得分:0)

只是做:

for(key,value) in tempJSON.enumerated(){
   print(key)
}

答案 2 :(得分:0)

我最好的猜测是你从你的userdefault中获取一个字符串并使用它来初始化JSON,尝试更改:

tempJSON = JSON(self.userdefaults.string(forKey: "currentOrder"))

tempJSON = JSON(self.userdefaults.dictionary(forKey: "currentOrder"))

答案 3 :(得分:0)

解 我不得不将parseJSON:添加到JSON方法中,以便告诉它来自字符串文字。

var tempJSON:JSON = ""
tempJSON = JSON(parseJSON: self.userdefaults.string(forKey: "currentOrder"))
print(tempJSON)
相关问题