gpt4 book ai didi

ios - 转换 JSON 嵌套对象

转载 作者:行者123 更新时间:2023-12-01 19:59:56 24 4
gpt4 key购买 nike

我从 Foursquare API 获得以下 JSON,并且一直在努力提取数据:

{
"meta":{
"code":200,
"requestId":"58122e59498e5506a1b23580"
},
"response":{
"venues":[
{
"id":"4d56c381a747b60cd4a12c2b",
"name":"Sports Circle",
"contact":{},
"location":{
"lat":31.9,
"lng":35.9,
"labeledLatLngs":[
{
"label":"display",
"lat":31.9,
"lng":35.90
}
],
],
"confident":true
}
}
}

我想得到 namevenues除了 latlng值(value)观。到目前为止,我已经尝试过了,但它超出了 JVenues 处的第二个 if 语句。因为它是 nil :
func parseData (JSONData: Data){
do {
var readableJson = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! [String:AnyObject]

if let JResponse = readableJson ["response"] as? [String:AnyObject] {
if let JVenues = JResponse["venues"] as? [String:AnyObject]{
if let JName = JVenues["name"] as? String{
NSLog(JName)
}
}
}
} catch {
print(error)
}
}

最佳答案

这就是其他答案的意思。如果您能看到所有内容,可能会更有意义...

if let JResponse = readableJson ["response"] as? [String : AnyObject] {
if let JVenues = JResponse["venues"] as? [[String : AnyObject]] {
if let JName = JVenues.first?["name"] as? String {
NSLog(JName)
}
}
}

请注意,这只会获取 field 数组中的第一个名称。

编辑:

我更喜欢这样的东西。定义一个结构并将您的字典转换为该结构:
struct Venue {
var name: String?
var venueId: String?

init(_ venueDictionary: [String : AnyObject]) {
self.name = venueDictionary["name"] as? String
self.venueId = venueDictionary["id"] as? String
}
}

在您的类(class)中创建一个属性,例如:
var venues = [Venue]()

从您的 JSON 映射字典到 field 数组。我重命名了以大写字母开头的变量以表示约定。
if let response = readableJson ["response"] as? [String : AnyObject] {
if let responseVenues = response["venues"] as? [[String : AnyObject]] {
self.venues = responseVenues.map({ Venue($0)) })
}
}

在类里面的任何地方使用,例如:
let venue = self.venues.first
print(venue?.name)

或者:
if let venue = self.venues.find({ $0.name == "Sports Circle" }) {
print("found venue with id \(venue.venueId)")
}

关于ios - 转换 JSON 嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40291373/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com