IOS中的JSON

JSON的全程是JavaScript Object Notation, 是一种轻量级的数据交换格式. JSON与XML具有相同的特性, 例如易于人们编写和阅读,易于机器生成和解析.但是JSON比XML数据传输的有效性要高出很多.JSON完全独立于编程语言,使用文本格式保存.

 

JSON 数据格式为

{name: "mazhao",

  array: {"array item 0", "array item 1", "array item 2"}} 

 

官方的文档对NSJSONSerialization的解释如下

You use the NSJSONSerialization class to convert JSON to Foundation objects and convert Foundation objects to JSON.

An object that may be converted to JSON must have the following properties:

  • The top level object is an NSArray or NSDictionary.
  • All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
  • All dictionary keys are instances of NSString.
  • Numbers are not NaN or infinity.

NSJSONSerialization 是用来将JSON转换为Foundation objects, 也可以将Foundation objects转换为JSON

一个对象如果可以被转换为JSON需要遵循以下几点:

1. 顶层的对象必须是一个NSArray或者是NSDictionary

2. 所有的对象必须是NSString,NSNumber,NSArray,NSDictionary或者NSNull的实例

3. 所有的Dictionary关键字必须是NSString的实例

4. 数字对象不能是非数值或无穷

接下来展示如何使用

1 NSDictionary *registerDic = [NSDictionary dictionaryWithObjectsAndKeys:uuid,@"_id",userName,@"login_name",password,@"password", nil];  
2     if ([NSJSONSerialization isValidJSONObject:registerDic]) {  
3         NSError *error;  
4         NSData *registerData = [NSJSONSerialization dataWithJSONObject:registerDic options:NSJSONWritingPrettyPrinted error:&error];  
5         NSLog(@"Register JSON:%@",[[NSString alloc] initWithData:registerData encoding:NSUTF8StringEncoding]);  
6     }  

NSDictionary中的key就是JSON中的key, object就是JSON中的value, isValidJSONObject:方法是检测Foundation是否能转换为JSON对象

dataWithJSONObject: options: error:是将Foundation对象转换为JSON对象, 参数NSJSONWritingPrettyPrinted是将生成的JSON格式化输出,这样设置可读性比较高,如果不设置该属性,则整行输出该JSON序列.

 

解析服务端返回的JSON序列

1 NSDictionary *resultJSON = [NSJSONSerialization JSONObjectWithData:resultData options:kNilOptions error:&error];  

返回字符串中value为"gogogo"的object

1 NSString *status = [resultJSON objectForKey:@"status"];  
posted @ 2014-02-25 16:48  tomios  阅读(122)  评论(0)    收藏  举报