[英]How can I loop through an object in SwiftyJSON? not just with swift
var tempJSON:JSON = ""
tempJSON = JSON(self.userdefaults.string(forKey: "currentOrder"))
print(tempJSON)
yields: 产量:
{"7": "1", "21": "0", "20": "0", "3": "1"}
I need to be able to loop through this and just can't. 我需要能够遍历这一点,但是不能。 I've tried.
我试过了。
for(key,value) in tempJSON{
print(key)
}
and nothing outputs.... 没有任何输出。
Thanks 谢谢
Try getting Data
from the string and use it to init the JSON
object: 尝试从字符串获取
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)
}
}
Just do: 做就是了:
for(key,value) in tempJSON.enumerated(){
print(key)
}
My best guess is that you are getting a string out from your userdefault and use it to init JSON
, try change: 我最好的猜测是您从userdefault中获取了一个字符串,并将其用于初始化
JSON
,请尝试更改:
tempJSON = JSON(self.userdefaults.string(forKey: "currentOrder"))
to 至
tempJSON = JSON(self.userdefaults.dictionary(forKey: "currentOrder"))
SOLUTION I had to add the parseJSON: to the JSON method so as to tell that is was coming from a string literal. 解决方案:我必须将parseJSON:添加到JSON方法中,以告诉它是来自字符串文字。
var tempJSON:JSON = ""
tempJSON = JSON(parseJSON: self.userdefaults.string(forKey: "currentOrder"))
print(tempJSON)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.