给定以下示例 JSON
{
"filters": [
{ "name" : "First Type",
"types" : ["md", "b", "pb"]},
{ "name" : "Second Type",
"types" : ["pt", "ft", "t"]},
{ "name" : "Third Type",
"types" : ["c", "r", "s", "f"]
}
],
"jobs": [
{ "title":"f",
"description" : "descrip text",
"criteria":[ "md", "ft", "s" ],
"img" : "www1"
},
{ "title":"boa",
"description" : "a description",
"criteria":[ "b", "pb", "f", "ft" ],
"img" : "www2"
},
{ "title":"BK",
"description" : "something here",
"criteria":[ "md", "pt", "ft", "b", "s" ],
"img" : "www3"
}
]
}
(使用 Alamofire 创建响应) 让 responseJSON : JSON = JSON(response.result.value!)
1) 我试图将它们转换成两个字符串数组。一个数组:let filter = [String : [String]] 和另一个数组用于作业。我该怎么做? (又名授人以鱼)以下是一些示例代码片段,但没有一个能正常工作。
let filterCategories = responseJSON["filters"].arrayValue.map({
$0["name"].stringValue
})
和
for (key,subJson):(String, JSON) in responseJSON["filters"] {
let object : filterObject = filterObject(category: key, list: subJson.arrayValue.map({ $0.stringValue }))
}
2) 我如何学习如何正确使用它? (又名授人以渔)我一直在阅读文档 ( https://github.com/SwiftyJSON/SwiftyJSON ),但我很难理解它。我猜最终答案将使用 .map、.stringValue 和 .arrayValue。最终,虽然我试图避免大量不必要或难以管理的代码。
最佳答案
Swift 4 提供开箱即用的 JSON 解析支持 - 可能从类似 Ultimate Guide to JSON Parsing with Swift 4 的内容开始
根据你的可用结构,我扔进了一个 Playground 并使用了......
// I was loading the JSON from a file within the Playground's Resource folder
// But basically, you want to end up with a reference to Data
let filePath = Bundle.main.path(forResource:"Source", ofType: "json")
let data = FileManager.default.contents(atPath: filePath!)
struct Filter: Codable {
let name: String;
let types: [String];
}
struct Job: Codable {
let title: String;
let description: String;
let criteria: [String];
let img: String;
}
struct Stuff: Codable {
let filters: [Filter];
let jobs: [Job];
}
let decoder = JSONDecoder();
let stuff = try! decoder.decode(Stuff.self, from: data!)
print("Filter:")
for filter in stuff.filters {
print(filter.name)
for type in filter.types {
print(" - \(type)")
}
}
print("Jobs:")
for job in stuff.jobs {
print(job.title)
print(job.description)
print(job.img)
for type in job.criteria {
print(" - \(type)")
}
}
解析结果
关于ios - SwiftyJSON 转换为多个字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51778343/