如何在数组的第二个索引处访问字典的href键的值?

时间:2017-11-28 17:00:52

标签: ios arrays swift dictionary

json数据如下:

 "links" : [ {
    "rel" : "item1",
    "href" : "data1"
  }, {
    "rel" : "item2",
    "href" : "data2"
  }, {
    "rel" : "item3",
    "href" : "data3"
  }, {
    "rel" : "item4",
    "href" : "data4"
  }, {
    "rel" : "item5",
    "href" : "data5"
  }, {
    "rel" : "item6",
    "href" : "data6"
  }, {
    "rel" : "item7",
    "href" : "data7"
  }, {
    "rel" : "item8",
    "href" : "data8"
  }, {
    "rel" : "item9",
    "href" : "data9"
  } ]
}

如何在Swift链接数组的第二个索引处访问值data2的href键?

1 个答案:

答案 0 :(得分:0)

您应首先构建数据并使其成为可编码数据。然后,您可以从API返回的数组中获取元素属性。请注意,字符串开头有一个缺少的括号:

struct Root: Codable {
    let links: [Links]
}
struct Links: Codable, CustomStringConvertible {
    let rel: String
    let href: String
    var description: String {
        return "Rel: \(rel) - Href: \(href)"
    }
}
let jsonData = Data("""
{"links" : [ {
    "rel" : "item1",
    "href" : "data1"
  }, {
    "rel" : "item2",
    "href" : "data2"
  }, {
    "rel" : "item3",
    "href" : "data3"
  }, {
    "rel" : "item4",
    "href" : "data4"
  }, {
    "rel" : "item5",
    "href" : "data5"
  }, {
    "rel" : "item6",
    "href" : "data6"
  }, {
    "rel" : "item7",
    "href" : "data7"
  }, {
    "rel" : "item8",
    "href" : "data8"
  }, {
    "rel" : "item9",
    "href" : "data9"
  } ]
}
""".utf8)
let decoder = JSONDecoder()
do {
    let root = try decoder.decode(Root.self, from: jsonData)
    print(root)  // Root(links: [Rel: item1 - Href: data1, Rel: item2 - Href: data2, Rel: item3 - Href: data3, Rel: item4 - Href: data4, Rel: item5 - Href: data5, Rel: item6 - Href: data6, Rel: item7 - Href: data7, Rel: item8 - Href: data8, Rel: item9 - Href: data9])
    let secondLinkHref = root.links[1].href  // "data2"
} catch {
    print(error)
}