iOS中NSJSONSerialization解析JSON数据暨google地理信息处理案例


在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"
}

  • 1
  • 2
  • 3
  • 下一页

相关内容