SwiftyJSON 转换为多个字符串数组

SwiftyJSON conversion to multiple string arrays

给定以下示例 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 创建响应) 让响应JSON : JSON = JSON(response.result.value!)

1) 我试图将它们转换成两个字符串数组。一个数组:let filter = [String : [String]] 和另一个数组用于作业。我该怎么做? (又名授人以鱼)以下是一些示例代码片段,但 none 甚至接近工作。

  let filterCategories = responseJSON["filters"].arrayValue.map({
          [=11=]["name"].stringValue
  })

for (key,subJson):(String, JSON) in responseJSON["filters"] {
    let object : filterObject = filterObject(category: key, list: subJson.arrayValue.map({ [=12=].stringValue }))

  }

2) 我如何学习如何正确使用它? (又名授人以渔)我一直在阅读文档 (https://github.com/SwiftyJSON/SwiftyJSON),但我很难理解它。我猜最终答案将使用 .map、.stringValue 和 .arrayValue。最终,虽然我试图避免大量不必要或难以管理的代码。

Swift 4 提供开箱即用的 JSON 解析支持 - 可能从 Ultimate Guide to JSON Parsing with Swift 4

之类的东西开始

根据你的可用结构,我扔进了一个游乐场并使用了...

// 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)")
    }
}

解析结果

您可以实施 Codable 协议来解析响应。使用您的 json 回复代替此

let url = Bundle.main.url(forResource: "data", withExtension: "json")
let data = NSData(contentsOf: url!)

我把它用在操场上进行测试。

struct Root: Codable {
   let jobs: [Jobs]
   let filters: [Filters]

private enum CodingKeys: String, CodingKey {
    case jobs = "jobs"
    case filters = "filters"
 }
}

struct Filters: Codable {
    let name: String?
    let typees: String?
}

struct Jobs: Codable {
     let title: String?
     let description: String?
     let criteria: [String]?
     let img: String? 
}

let url = Bundle.main.url(forResource: "data", withExtension: "json")
let data = NSData(contentsOf: url!)


do {
      let root = try JSONDecoder().decode(Root.self, from: data as! Data)

      if let name = root.jobs.first?.title {
      print(name)
      }


} catch let error as NSError {

   print(error.description)
}