如何从 JSON 数组中获取字符串数组? [关闭]
Posted
技术标签:
【中文标题】如何从 JSON 数组中获取字符串数组? [关闭]【英文标题】:How to get an string array from JSON arrays? [closed] 【发布时间】:2017-05-07 06:04:30 【问题描述】:嗯,我有一个服务器响应:
cars = (
"color" = red;
"model" = ferrari;
"othersAtributes" = others atributes;
,
"color" = blue;
"model" = honda;
"othersAtributes" = others atributes;
,
"color" = green;
"model" = ford;
"othersAtributes" = others atributes;
,
"color" = yellow;
"model" = porshe;
"othersAtributes" = others atributes;
)
我需要一份模型车清单。一组模型汽车,设置为列表。
【问题讨论】:
【参考方案1】:首先,您需要将来自服务器的原始响应转换为 Swift Dictionary
。
let payload = [
"cars": [
[
"color": "red",
"model": "ferrari",
"othersAtributes": "others atributes"
],
[
"color": "blue",
"model": "honda",
"othersAtributes": "others atributes"
],
[
"color": "green",
"model": "ford",
"othersAtributes": "others atributes"
],
[
"color": "yellow",
"model": "porshe",
"othersAtributes": "others atributes"
]
]
]
然后
let models: [String] = payload["cars"]!.map( $0["model"] as! String )
print(models)
会给你["ferrari", "honda", "ford", "porshe"]
。
(您可能希望用更安全的错误处理机制替换强制解包!
。)
【讨论】:
如何转换?像这样?let payload = response as? [String: Any]
?
我假设服务器有效负载是标准 JSON 格式,并且您使用 NSURLSessionDataTask
请求它,以便您获得一个 Data
对象。那么答案将是@Vignesh J 发布的内容。虽然我建议使用 [String: Any]
来更 Swift-y。 let payload: [String: Any]= NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! [String: Any]
我用 alamofire 做的
并且响应是任意对象
您应该能够将AnyObject
转换为Dictionary
。我认为这是一个完美的例子github.com/Alamofire/Alamofire/blob/…【参考方案2】:
试试这个 sn-p。没有完美测试。我猜汽车是一个数组:
var modelsArray = [String]()
for index in cars.enumerated()
let model = cars[index].value(forKey: "model")
modelsArray.append(model)
【讨论】:
以上是关于如何从 JSON 数组中获取字符串数组? [关闭]的主要内容,如果未能解决你的问题,请参考以下文章
如何创建一个 Flutter Futurebuilder 函数来显示从 JSON 中获取的字符串数组?
如何从带有 ios Swift 3 的肥皂 Web 服务方法中获取 json 数组字符串?