歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> iOS中NSJSONSerialization解析JSON數據暨google地理信息處理案例

iOS中NSJSONSerialization解析JSON數據暨google地理信息處理案例

日期:2017/3/1 10:00:01   编辑:Linux編程

在iOS開發中,涉及到從網絡取得json格式的數據處理工作時,我們會想到很多開源的第三方包,如SBJSON。在iOS5開始,也增加了對json格式數據的處理能力,增加的類是NSJSONSerialization。

使用NSJSONSerialization,可以分析各種復雜格式json數據。

使用的類方法是+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error。
根據不同data的結構,設置不同的option。這裡option有三類:NSJSONReadingMutableContainers, NSJSONReadingMutableLeaves , NSJSONReadingAllowFragments。
apple文檔對這三種方法做了說明。
1、NSJSONReadingMutableContainers
Specifies that arrays and dictionaries are created as mutable objects.
2、NSJSONReadingMutableLeaves
Specifies that leaf strings in the JSON object graph are created as instances of NSMutableString.
3、NSJSONReadingAllowFragments
Specifies that the parser should allow top-level objects that are not an instance of NSArray or NSDictionary.
Available in iOS 5.0 and later.

我就http://maps.googleapis.com/maps/api/geocode/json?address=nanjing&sensor=true這個鏈接做了測試。這是google的地理信息api,根據地點得到經緯度等信息。

這個url得到的json格式的結果如下所示:

{
"results" : [
{
"address_components" : [
{
"long_name" : "南京",
"short_name" : "南京",
"types" : [ "locality", "political" ]
},
{
"long_name" : "江蘇省",
"short_name" : "江蘇省",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "中國",
"short_name" : "CN",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "中國江蘇省南京市",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 32.61436330,
"lng" : 119.23624250
},
"southwest" : {
"lat" : 31.22809770,
"lng" : 118.36337310
}
},
"location" : {
"lat" : 32.0602550,
"lng" : 118.7968770
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 32.39401350,
"lng" : 119.0501690
},
"southwest" : {
"lat" : 31.80452470,
"lng" : 118.42533230
}
}
},
"types" : [ "locality", "political" ]
}
],
"status" : "OK"
}

Copyright © Linux教程網 All Rights Reserved