ios 如何使用 SwiftyJSON 解析字符串数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27102666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to parse string array with SwiftyJSON?
提问by The Nomad
Using SwiftyJSON
how would I parse the following JSON array into a Swift [String]
?
使用SwiftyJSON
如何将以下 JSON 数组解析为Swift [String]
?
{
"array": ["one", "two", "three"]
}
I have tried this code, but it doesn't work for me:
我试过这段代码,但它对我不起作用:
for (index: String, obj: JSON) in json["array"] {
println(obj.stringValue)
}
What would be the best way to handle this? Thank you.
处理这个问题的最佳方法是什么?谢谢你。
回答by Gwendle
{
"myArray": ["one", "two", "three"]
}
Using SwiftyJSON, you can get an array of JSON objects with:
使用 SwiftyJSON,您可以获得一组 JSON 对象:
var jsonArr:[JSON] = JSON["myArray"].arrayValue
Functional programming then makes it easy for you to convert to a [String] using the 'map' function. SwiftyJson let's you cast string type with subscript '.string'
然后,函数式编程使您可以轻松地使用 'map' 函数将其转换为 [String]。SwiftyJson 让你用下标“.string”来转换字符串类型
var stringArr:[String] = JSON["myArray"].arrayValue.map { for obj in json["array"] {
println(obj.stringValue)
}
.stringValue}
回答by jfgrang
SwiftyJSON lets you extract a String?
using $0.string or a non optional String
using stringValue with a default empty String value if the type doesn't match.
如果类型不匹配,SwiftyJSON 允许您提取String?
using $0.string 或非可选String
using stringValue 和默认空 String 值。
If you want to be sure to have an array of String with non false positives, use :
如果您想确保有一个非误报的字符串数组,请使用:
var stringArray = self.json["array"].array?.flatMap({ $0.string })
var stringArray = self.json["array"].array?.flatMap({ $0.string })
or in Swift 4.1
或在 Swift 4.1
var stringArray = self.json["array"].array?.compactMap({ $0.string })
var stringArray = self.json["array"].array?.compactMap({ $0.string })
You can also replace self.json["array"].array
by self.json["array"].arrayValue
to have a [String]
result instead of [String]?
.
您也可以替代self.json["array"].array
由self.json["array"].arrayValue
有[String]
结果,而不是[String]?
。
回答by Jeffery Thomas
You have a Dictionary
which holds an Array
which holds String
s. When you access a value in the Dictionary
, it returns a simple Array
of String
s. You iterate it like you would any array.
你有一个Dictionary
持有一个Array
持有String
s。当您访问 中的值时Dictionary
,它返回一个简单Array
的String
s。你像迭代任何数组一样迭代它。
for stringInArray in json["array"]{
let value = stringInArray.1.stringValue
}
回答by Yaron Levi
Simply do this:
只需这样做:
##代码##