gpt4 book ai didi

json - 解析 JSON - Swift

转载 作者:行者123 更新时间:2023-11-28 06:09:01 25 4
gpt4 key购买 nike

我正在使用以下源代码从 Google map 中检索一些数据:

import UIKit
import GoogleMaps
import GooglePlaces
import SwiftyJSON

class Place /*: NSObject*/ {
let name: String

init(diction:[String : Any])
{
let json = JSON(diction)
name = json["name"].stringValue //as! String
}
}

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

var urlString = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?&location=54.507514,-0.073603&radius=1000&name=Specsavers&name=Opticians&key=AIzaSyAcXLd8jotAyIOgKYqhYbL703BIibXkd-M"

guard let url = URL(string: urlString) else {return}

URLSession.shared.dataTask(with: url) {(data, response, error) in

if let content = data {
do {
let json = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
if let results = json["results"] as? [[String : Any]] {
var places = [Place]()
for place in results {
print("HERE0: " place)
places.append(Place(diction: place))
}
print("HERE1:", places)
}
else {
print("return")
}

}
catch{

}
}
}.resume()

}

但是当我尝试打印地点时,我得到以下响应:

2017-11-13 11:16:56.887909+0000 Trial[3911:127944] [BoringSSL] Function boringssl_context_get_peer_sct_list: line 1757 received sct extension length is less than sct data length

我从 HERE1 得到这个输出:

HERE1: [Trial.Place](我的xcode项目命名为Trial)

虽然我从 HERE0 得到了正确的 json 文件。

为什么我无法从 Google Places 正确检索商店名称?

最佳答案

您的错误是,places 实际上是一个 Place 类数组。所以当你打印出来时你应该指定一个索引。因为它是一个类数组,所以在索引之后你应该输入你想看到的属性。

我重构了你的代码,你可以使用它。

你的类文件

class Place /*: NSObject*/ {
let name: String

init(diction:[String : Any])
{
self.name = diction["name"] as! String
}
}

你的 json 解析

 var places = [Place]() //do it outside of the viewDidload


let urlString = URL(string: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?&location=51.507514,-0.073603&radius=1000&name=Specsavers&name=Opticians&key=AIzaSyAcXLd8jotAyIOgKYqhYbL703BIibXkd-M")

let session = URLSession.shared
let task = session.dataTask(with: urlString!) { (data, response, err) in
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableLeaves) as! Dictionary<String,Any>
if let results = json["results"] as? [[String:Any]] {
for place in results {
self.places.append(Place(diction: place))
print(self.places[0].name)
}
print(self.places[0].name)
}
}catch let err{
print(err)
}

}
}
task.resume()

关于json - 解析 JSON - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47263276/

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