JSON 语法 及 解析

JSON

是一种轻量级的数据交换格式

从结构上看,所有的数据(data)最终都可以分解成三种类型:

  1. 第一种类型是标量(scalar),也就是一个单独的字符串(string)或数字 (numbers),比如”北京”这个单独的词
  2. 第二种类型是序列(sequence),也就是若干个相关的数据按照一定顺序并列在一 起,又叫做数组(array)或列表(List),比如”北京,上海”
  3. 第三种类型是映射(mapping),也就是一个名/值对(Name/value),即数据有一个 名称,还有一个与之相对应的值,这又称作散列(hash)或字典(dictionary),比 如”首都:北京”

Douglas Crockford发明了JSON,Json的规定非常简单:

  1. 并列的数据之间用逗号”, “分隔
  2. 映射用冒号”: “表示
  3. 并列数据的集合(数组)用方括号”[]”表示
  4. 映射的集合(对象)用大括号”{}”表示

JSON模式举例

[

 {
 "precision": "zip",
 "Latitude":  37.7668,
 "Longitude": -122.3959,
 "Address":   "",
 "City":      "SAN FRANCISCO",
 "State":     "CA",
 "Zip":       "94107",
 "Country":   "US"
 },
 {
 "precision": "zip",
 "Latitude":  37.371991,
 "Longitude": -122.026020,
 "Address":   "",
 "City":      "SUNNYVALE",
 "State":     "CA",
 "Zip":       "94085",
 "Country":   "US"
 }
 ]

英文官方文档:http://www.ietf.org
中文注解网址:http://www.json.org/json-zh.htm
用来检测是否为JSON格式:http://www.sojson.com

NSJSONSerialization
//把数据转换成JSON模型,options参数一般为 NSJSONReadingAllowFragments
+ (id)JSONObjectWithData:(NSData *)dataerror:(NSError **)error
options:(NSJSONReadingOptions)opt
error:(NSError **)error
//把JSON模型转换成数据
+ (NSData *)dataWithJSONObject:(id)obj
options:(NSJSONWritingOptions)opt

JSONKit(第三方的,不如上边的系统的好使)

在github上直接搜索jsonkit,然后下载到本地,打开后拷贝.h和.m文件到工程中,点击运行,会报出很多错误,因为jsonkit是在非arc环境下编写的,所以还要进行设置,让编译的时候对jsonkit不使用arc

这里写图片描述

序列化: NSArray NSDictionary NSString
对上边的对象发送下面的消息,会转化成对应格式的JSONData

JSONData
– JSONDataWithOptions:includeQuotes:error:
-
JSONDataWithOptions:serializeUnsupportedClassesUsingDelegate:selector:error:
- JSONDataWithOptions:serializeUnsupportedClassesUsingBlock:error:
– JSONString
– JSONStringWithOptions:includeQuotes:error:
-
JSONStringWithOptions:serializeUnsupportedClassesUsingDelegate:selector:error:
– JSONStringWithOptions:serializeUnsupportedClassesUsingBlock:error:

反序列化: NSData NSString
对上边的对象发送下面的消息,会转化成对应的 NSArray NSDictionary NSString

– objectFromJSONData
– objectFromJSONDataWithParseOptions:
– objectFromJSONDataWithParseOptions:error:
– mutableObjectFromJSONData
– mutableObjectFromJSONDataWithParseOptions:
– mutableObjectFromJSONDataWithParseOptions:error:
– objectFromJSONString
– objectFromJSONStringWithParseOptions:
– objectFromJSONStringWithParseOptions:error:
– mutableObjectFromJSONString
– mutableObjectFromJSONStringWithParseOptions:
– mutableObjectFromJSONStringWithParseOptions:error:


网页源代码中</table>包裹起来的代表表格,</tr>包裹起来的代表表格中的一行

代码举例

#import "ViewController.h"
#import "JSONKit.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *cityName;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    //下载和上传json数据主要用到一个类,NSJSONSerialization,进行数据转换,任务-NSURLSession类,分下载-NSURLSessionDataTask 和上传-NSURLSessionUploadTask
    //1.下载的举例:
    NSDictionary *dict = @{@"zhengzhou":@"101180101"};

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.weather.com.cn/adat/cityinfo/%@.html",dict[_cityName.text]]];
    //创建一个任务对象
    NSURLSession *session = [NSURLSession sharedSession];
    //创建下载任务
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error) {
            NSLog(@"error >> %@",error);
            return ;
        }
        //把数据转化成json对象
        id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves | NSJSONReadingAllowFragments error:&error];
        //打印对象中的数据
        NSLog(@"obj >> %@",obj);
        NSLog(@"cityname >> %@",obj[@"weatherinfo"][@"city"]);
        NSLog(@"cityname >> %@",obj[@"weatherinfo"][@"cityid"]);

    }];
    //启动下载任务
    [dataTask resume];

    //2.上传的举例:
    //假设我们的数据是:
    NSArray *array = @[@"poppei",@30,@"410000"];
    NSError *error1;
    //把基本类型的对象转换成json的数据格式
    NSData *data1 = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error1];
    //创建一个任务对象
    NSURLSession *session1 = [NSURLSession sharedSession];
    //上传任务(这里用nil,只是举例,应该是有一个具体的值)
    NSURLSessionUploadTask *uploadTask = [session1 uploadTaskWithRequest:nil fromData:data1];

    NSString *dataStr = [[NSString alloc]initWithData:data1 encoding:NSUTF8StringEncoding];
    NSLog(@"datastr >> %@",dataStr);
    //启动上传任务
    [uploadTask resume];
}

#pragma mark - 利用JSONKit

- (IBAction)searchWeather:(UIButton *)sender {

    NSDictionary *dict = @{@"zhengzhou":@"101180101"};
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.weather.com.cn/adat/cityinfo/%@.html",dict[_cityName.text]]];
    //创建一个任务对象
    NSURLSession *session = [NSURLSession sharedSession];
    //创建下载任务
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error) {
            NSLog(@"error >> %@",error);
            return ;
        }
        //使用jsonkit把json数据转化成对象
        id obj = [data objectFromJSONData];//此处用到JSONKit中的方法
        //打印对象中的数据
        NSLog(@"obj >> %@",obj);
        NSLog(@"cityname >> %@",obj[@"weatherinfo"][@"city"]);
        NSLog(@"cityname >> %@",obj[@"weatherinfo"][@"cityid"]);
    }];
    [dataTask resume];

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值