我正在使用Google的geolocator API自動映射某些內容。它在請求中返回一個JSON字符串,但我在分析它時遇到了很多困難。我嘗試過像Freddy和SwiftyJSON這樣的東西,但無法提取我想要的字段。Swift JSON解析 - 無法訪問字段/返回無
這裏是我的代碼示例:
func sendJsonRequest(ConnectionString: String,
HTTPMethod : HttpMethod = HttpMethod.Get,
JsonHeaders : [String : String] = [ : ],
JsonString: String = "") -> NSData? {
// create the request & response
let request = NSMutableURLRequest(URL: NSURL(string: ConnectionString)!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5)
// create some JSON data and configure the request
let jsonString = JsonString;
request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
// handle both get and post
request.HTTPMethod = HTTPMethod.rawValue
// we'll always be sending json so this is fine
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
// add the headers. If there aren't any then that's ok
for item in JsonHeaders {
request.addValue(item.1, forHTTPHeaderField: item.0)
}
print("Request:")
print(request)
let session = NSURLSession.sharedSession()
var data : NSData?
var urlTask = session.dataTaskWithRequest(request) { (Data, Response, Error) in
data = Data
}
urlTask.resume()
while (data == nil) {
}
return data
}
// return the coordinates of a given location
func getCoordinates() -> Coordinates {
var result = Coordinates()
let ConnectionString = "https://maps.googleapis.com/maps/api/geocode/json?address=43201"
let jsondata = sendJsonRequest(ConnectionString)
let data = jsondata
let json = JSON(data!)
print(json)
return result
}
getCoordinates()
下面是輸出的,我從一個單獨的JSON的客戶端得到的一個例子:
{
"results": [
{
"address_components": [
{
"long_name": "43201",
"short_name": "43201",
"types": [
"postal_code"
]
},
{
"long_name": "Columbus",
"short_name": "Columbus",
"types": [
"locality",
"political"
]
},
{
"long_name": "Franklin County",
"short_name": "Franklin County",
"types": [
"administrative_area_level_2",
"political"
]
},
{
"long_name": "Ohio",
"short_name": "OH",
"types": [
"administrative_area_level_1",
"political"
]
},
{
"long_name": "United States",
"short_name": "US",
"types": [
"country",
"political"
]
}
],
"formatted_address": "Columbus, OH 43201, USA",
"geometry": {
"bounds": {
"northeast": {
"lat": 40.011147,
"lng": -82.9723898
},
"southwest": {
"lat": 39.976962,
"lng": -83.0250691
}
},
"location": {
"lat": 39.9929821,
"lng": -83.00122100000002
},
"location_type": "APPROXIMATE",
"viewport": {
"northeast": {
"lat": 40.011147,
"lng": -82.9723898
},
"southwest": {
"lat": 39.976962,
"lng": -83.0250691
}
}
},
"place_id": "ChIJ9Rz24rWOOIgR3EEuL2Ge4oo",
"types": [
"postal_code"
]
}
],
"status": "OK"
}
我試圖讓現場結果.geometry.location。使用Freddy JSON解析庫,我能夠獲得結果字段,但無法訪問幾何字段。有人可以看看這個,看看我做錯了什麼嗎? SwiftyJSON甚至不讓我解析JSON。
感謝您的提示!不幸的是,這並不能解決我的json解析問題,但很高興知道我可以通過回調將該數據傳遞迴UI。 –
@FKunecke,我更新瞭解析正確的答案。你的方法在操場上可能看起來更好,但在現實生活中,你的實現會阻止會導致應用程序的UI凍結的主線程。 –