SwiftyJSON转换为多个字符串数组

时间:2018-08-10 03:05:30

标签: ios arrays swift swifty-json

给出以下示例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)我正在尝试将它们转换为两个String数组。一个数组: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。最终,尽管我试图避免大量不必要或无法管理的代码。

2 个答案:

答案 0 :(得分:1)

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

分析结果

答案 1 :(得分:1)

您可以实现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)
}