Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/107.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 快速JSON到多字符串数组的转换_Ios_Arrays_Swift_Swifty Json - Fatal编程技术网

Ios 快速JSON到多字符串数组的转换

Ios 快速JSON到多字符串数组的转换,ios,arrays,swift,swifty-json,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"] }

给定以下示例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
  })


2) 我如何学习如何正确使用它?(又名教人钓鱼)我一直在阅读文档(),但我很难理解它。我猜最终的答案将使用.map、.stringValue和.arrayValue。最终,尽管我试图避免大量不必要或不可管理的代码

Swift 4提供了现成的JSON解析支持,可以从以下内容开始

根据你可用的结构,我扔到一个操场,并使用

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

解析结果

Swift 4提供了JSON解析的开箱即用支持,可以从以下内容开始

根据你可用的结构,我扔到一个操场,并使用

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

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

如果您使用的是Swift 4,那么请看一看如果您使用的是Swift 4,那么请看一看感觉像伏都教魔法。stuff.filters和stuff.jobs保存着我正在寻找的数据。是的,是的,确实如此,但它(非常)受欢迎地改变了之前的活动中必须做的每一件事,尽管SwiftyJSON非常棒,但这要好得多-我向通过此问题/答案的任何人发出提示:这对我来说一瞬间都不明显,但“结构”JSON的类型需要与所涉及的结构的类型匹配。例如,如果我选择在JSON文件中将“jobs”更改为“abc”,则结构也需要更改(“let jobs”变为“let abc”)。此外,我在构建嵌套数组时使用了这个答案。@Alex You“可能”能够编写自己的“coder”,这在中的“自定义键名”部分中进行了演示;)感觉像巫术。stuff.filters和stuff.jobs保存着我正在寻找的数据。是的,是的,确实如此,但它(非常)受欢迎地改变了之前的活动中必须做的每一件事,尽管SwiftyJSON非常棒,但这要好得多-我向通过此问题/答案的任何人发出提示:这对我来说一瞬间都不明显,但“结构”JSON的类型需要与所涉及的结构的类型匹配。例如,如果我选择在JSON文件中将“jobs”更改为“abc”,则结构也需要更改(“let jobs”变为“let abc”)。此外,我在构建嵌套数组时使用了这个答案。@Alex You“可能”能够编写自己的“coder”,这在中的“自定义键名”部分中进行了演示;)