JSON KVC 初探

JSONKVC 初探

 

1, 简单的JSON解析

文中使用原生的 NSJSONSerialization类来解析json字符串,并利用KVC机制来映射相应属性对象。

NSString* jsonString =@"[{\"id\":1,\"name\":\"Paul McCartney\",\"age\":73,\"height\":172},{\"id\":2,\"name\":\"Mark\",\"age\":53,\"height\":180}]";

 

NSData* jsonData = [jsonStringdataUsingEncoding:NSUTF8StringEncoding];

 

首先定义了一个NSString类型的json串。

然后,将其转化为NSData类型对象, NSJSONSerialization类里有两个将Json解析成Foundation Objects的方法,这里用到的是JSONObjectWidthData方法

所以用到NSData

 

//解析

NSError* error;

NSArray * jsonArray = [NSJSONSerializationJSONObjectWithData: jsonData options: NSJSONReadingMutableContainers error:&error];

 

options参数使用的是

NSJSONReadingMutableContainer 指定创建的可变对象为NSArray或NSDictionary。

    

另外两个可选择的参数:

NSJSONReadingMutableLeaves: 指定JSON树上的子数据为NSMutableString类型的对象

NSJSONReadingAllowFragments: 指定JSON顶层的对象可以不是NSArray或NSDictionary类型的对象

 

//输出 

if(jsonArray){

   for(NSDictionary*playerInfo in jsonArray){

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

   }

}

 

控制台输出结果:

playerInfo: {

    age =73;

    height= 172;

    id = 1;

    name ="Paul McCartney";

}

 

2,将FoundationObjects对象转化为JSON

 

if([NSJSONSerializationisValidJSONObject:jsonArray])

{

        jsonData = [NSJSONSerializationdataWithJSONObject:jsonArray options:NSJSONWritingPrettyPrintederror:&error];

        jsonString =[[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];

       

       NSLog(@"jsondata:%@",jsonString);

 }

 

1,isValidJSONObject方法首先检测jsonArray是否可转化为JSON对象。

2,将NSDictionary或NSArray转化为JSON时用到参数NSJSONWritingPrettyPrinted的作用是在输出时增加空格,增加输出内容的可读性。

 

NOTE:

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

    1,The top level object is an NSArray or NSDictionary. 顶层对象必须是NSArray或NSDictionary

    2,All objects areinstances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.

    3,All dictionary keys are instances of NSString.

   4,Numbers are not NaN or infinity.

 

3,KVC映射

 

 

//main.m

NSString*jsonString = @"{\"playerList\":[{\"id\":18,\"name\":\"AdiKing-A\",\"age\":27,\"height\":166},{\"id\":20,\"name\":\"Mark-B\",\"age\":22,\"height\":185}]}";

NSData*jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

   

NSError*error;

NSDictionary*dataDic = [NSJSONSerialization JSONObjectWithData: jsonData options:NSJSONReadingMutableContainers error: &error];

 

这里做了一些简单的修改,最原JSON串外,套了一层playerList属性。

 

接着来写PlayerInfo类

 

//PlayerInfo.h

#import<Foundation/Foundation.h>

 

@interfacePlayerInfo : NSObject

@property(nonatomic,strong) NSNumber* id;

@property(nonatomic,strong) NSString* name;

@property(nonatomic,strong) NSNumber* age;

@property(nonatomic,strong) NSNumber* height;

 

-(id)initWith:(NSDictionary*) playerInfoDic;

@end

 

//PlayerInfo.m

#import"PlayerInfo.h"

 

@implementationPlayerInfo

 

-(id)initWith:(NSDictionary *)playerInfoDic

{

    if(self = [super init]){

        [selfsetValuesForKeysWithDictionary:playerInfoDic];

    }

   

    return self;

}

 

-(NSString*) description

{

    return [NSStringstringWithFormat:@"player info ===>id=%@,name=%@,age=%@,weight=%@",self.id,self.name,self.age,self.height];

}

@end

 

//main.m

NSArray*playerInfoList = [dataDic objectForKey:@"playerList"];

for(inti=0;i < playerInfoList.count;i++)

{

        NSDictionary* playerInfoDic =[playerInfoList objectAtIndex:i];

        PlayerInfo* playerInfo = [[PlayerInfoalloc]initWith:playerInfoDic];

       NSLog(@"%@",playerInfo);

}

 

//输出

playerinfo ===> id=18,name=AdiKing-A,age=27,weight=166

playerinfo ===> id=20,name=Mark-B,age=22,weight=185

 

JSON成功映射到PlayerInfo类的Foundation Objects 对象上。

大功告成,来看看发生了什么。

 

我们在PlayerInfo上定义了四个属性,并自定义了一个初始化方法(initWith)。

方法里,我们利用KVC模式中的setValuesForKeyWithDictionary方法,映射PlayerInfo里的属性。

 

//出错

若此时我们在JSON串里加一个PlayerInfo里没有的属性会发生什么呢?比如改成如下:

 

NSString*jsonString = @"{\"playerList\":[{\"id\":18,\"name\":\"AdiKing-A\",\"age\":27,\"height\":166,\"years\":1980},{\"id\":20,\"name\":\"Mark-B\",\"age\":22,\"height\":185}]}";

 

运行程序,控制台会报错。

 

*** Terminating app due to uncaughtexception 'NSUnknownKeyException', reason:'[<PlayerInfo 0x1003004d0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key years.'

 

在PlayerInfo类里重写 setUndefinedKey方法。

 

-(void)setValue:(id)value forUndefinedKey:(NSString *)key

{

    NSLog(@"UndefinedKey=====>%@",key);

}

 

然后运行,异常消息,控制台输出:

//输出

UndefinedKey=====>years

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值