【发布时间】:2016-07-15 20:10:55
【问题描述】:
我正在使用 Google 的地理定位器 API 来自动映射一些东西。它在请求中返回一个 JSON 字符串,但我在解析它时遇到了很多困难。我尝试过 Freddy 和 SwiftyJSON 之类的东西,但都无法提取我想要的字段。
这是我的代码示例:
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"
}
我正在尝试获取字段 results.geometry.location。使用 Freddy JSON 解析库,我能够获取结果字段,但无法访问几何字段。有人可以看看这个,看看我做错了什么吗? SwiftyJSON 甚至不允许我解析 JSON。
【问题讨论】:
标签: json swift swifty-json