iOS中JSON数据解析

使用方法:

    NSDictionary *testDic = [[NSDictionary alloc] initWithObjectsAndKeys:@"0",@"result",@"1020",@"bizCode",@"success",@"data", nil];

    NSLog(@"testDic:%@",testDic);

    NSError *error;

    NSData *jsonData;

    if ([NSJSONSerialization isValidJSONObject:testDic]) {

        jsonData = [NSJSONSerialization dataWithJSONObject:testDic options:0 error:&error];

        NSLog(@"jsonData:%@",jsonData);

NSLog(@"error :%@",error.localizedDescription);

    }


    NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

    NSLog(@"jsonStr:%@",jsonStr);

    NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];

    NSLog(@"jsonDic:%@",jsonDic);


NSJSONSerialization接口说明

官方为我们提供的解析JSON数据的类是NSJSONSerialization,首先我们先来看下这个类的几个方法:

 + (BOOL)isValidJSONObject:(id)obj;

判断一个数据对象是否可以转化为JSON数据

 

+ (NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error;

将JSON数据写为NSData数据,其中opt参数的枚举如下,这个参数可以设置,也可以不设置,如果设置,则会输出视觉美观的JSON数据,否则输出紧凑的JSON数据。

typedef NS_OPTIONS(NSUIntegerNSJSONWritingOptions) {
    NSJSONWritingPrettyPrinted = (1UL << 0)
}

 

+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;

这个方法是解析中数据的核心方法,data是JSON数据对象,可以设置一个opt参数,具体用法如下:

typedef NS_OPTIONS(NSUIntegerNSJSONReadingOptions) {
    //将解析的数组和字典设置为可变对象
    NSJSONReadingMutableContainers = (1UL << 0),
    //将解析数据的子节点创建为可变字符串对象
    NSJSONReadingMutableLeaves = (1UL << 1),
    //允许解析对象的最上层不是字典或者数组
    NSJSONReadingAllowFragments = (1UL << 2)
}

 

+ (NSInteger)writeJSONObject:(id)obj toStream:(NSOutputStream *)stream options:(NSJSONWritingOptions)opt error:(NSError **)error;

将JSON数据写入到输出流,返回的是写入流的字节数

 

+ (id)JSONObjectWithStream:(NSInputStream *)stream options:(NSJSONReadingOptions)opt error:(NSError**)error;

从输入流读取JSON数据

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值