ios中使用 NSJSONSerialization对 json数据的解析

ios5中apple增加了解析JSON的api——NSJSONSerialization。通过该类,我们可以完成JSON数据与NSDictionaryNSArray之间的转化。网上已经有人做过测试,NSJSONSerialization在效率上完胜SBJSON、TouchJSON、YAJL、JSONKit、NextiveJson。

NSJSONSerialization提供了将JSON数据转换为Foundation对象(一般都是NSDictionary和NSArray)和Foundation对象转换为JSON数据(可以通过调用isValidJSONObject来判断Foundation对象是否可以转换为JSON数据)。

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式它基于ECMAScript的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C、C++、C#Java、JavaScript、PerlPython等)。这些特性使JSON成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成(网络传输速率)。

iOS中从服务器获得json数据是需要解析转换为Foundation对象(一般都是NSDictionary和NSArray)才能使用,同样的Foundation对象也是可以转换为json数据的,这时候使用NSJSONSerialization就非常的方便了。

官方为我们提供的解析JSON数据的类NSJSONSerialization的几个方法:

+ (BOOL)isValidJSONObject:(id)obj;

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

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

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

?
1
2
3
typedef  NS_OPTIONS(NSUInteger, NSJSONWritingOptions) {
     NSJSONWritingPrettyPrinted = (1UL << 0)
}

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

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

?
1
2
3
4
5
6
7
8
typedef  NS_OPTIONS(NSUInteger, NSJSONReadingOptions) {
     //将解析的数组和字典设置为可变对象
     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数据



json数据转换为Foundation对象

  1. -(void) parseJsonData:(NSData *)data  
  2. {  
  3.     //将NSString转化为NSData 拿到的json串需要先转化为NSData类型 才可以进行解析 !!!
  4.     NSError *error;  
  5.     NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];  
  6.     if (json == nil) {  
  7.         NSLog(@"json parse failed \r\n");  
  8.         return;  
  9.     }  
  10.     NSArray *songArray = [json objectForKey:@"song"];  
  11.     NSLog(@"song collection: %@\r\n",songArray);  
  12.   
  13.     _song = songArray;  
  14.     self.songIndex = 0;  
  15.     NSDictionary *song = [songArray objectAtIndex:0];  
  16.     NSLog(@"song info: %@\t\n",song);  

Foundation对象转换为json数据

[javascript]  view plain copy
  1. View Code   
  2.   
  3. NSDictionary *song = [NSDictionary dictionaryWithObjectsAndKeys:@"i can fly",@"title",@"4012",@"length",@"Tom",@"Singer", nil];  
  4.     if ([NSJSONSerialization isValidJSONObject:song])  
  5.     {  
  6.         NSError *error;  
  7. ///将JSON数据写为NSData数据
  8.         NSData *jsonData = [NSJSONSerialization dataWithJSONObject:song options:NSJSONWritingPrettyPrinted error:&error];  
  9.         NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];  
  10.         NSLog(@"json data:%@",json);  
  11.     }  
JSON串转化为NSDictionaryNSArray
//将NSString转化为 NSData 拿到的json串需要先转化为NSData类型 才可以进行解析 !!!

[jsonString dataUsingEncoding:NSASCIIStringEncoding];



// JSON串转化为字典或者数组

- (id)toArrayOrNSDictionary:(NSData *)jsonData{

    NSError *error = nil;

    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData

                                                    options:NSJSONReadingAllowFragments

                                                      error:&error];

    

    if (jsonObject != nil && error == nil){

        return jsonObject;

    }else{

        // 解析错误

         return nil;

    }


}


将JSON串与NSArray和NSDictionary的操作进行封装

当然,也有很多时候,我们将这些操作,分别定义在 NSObject和NSString的一个分类中

直接贴:

1.将NSString转化为NSArray或者NSDictionary

#import "NSString+JSONCategories.h"


@implementation NSString(JSONCategories)


-(id)JSONValue;

{

    NSData* data = [self dataUsingEncoding:NSUTF8StringEncoding];

    __autoreleasing NSError* error = nil;

    id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

    if (error != nilreturn nil;

    return result;

}

@end



2.将NSArray或者NSDictionary转化为NSString

#import "NSObject+JSONCategories.h"


@implementation NSObject (JSONCategories)


-(NSData*)JSONString;

{

    NSError* error = nil;

    id result = [NSJSONSerialization dataWithJSONObject:self

                                                options:kNilOptions error:&error];

    if (error != nilreturn nil;

    return result;

}

@end


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值