您的位置:首页 > 移动开发 > Objective-C

IOS开发学习27 ObjectC 自带json解析方法的使用

2015-05-29 08:11 706 查看
1.生成json字符串

NSMutableDictionary * header=[NSMutableDictionary dictionaryWithObjectsAndKeys:@"2015-02-03 19:15:00",@"timestamp",nil];

NSError *error=nil;
NSData *jsonData=[NSJSONSerialization dataWithJSONObject:header options:kNilOptions error:&error];
NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];


2.从NSString解析出json

NSData* data=[msg dataUsingEncoding:NSUTF8StringEncoding];
NSError *error=nil;
id json=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
if([json isKindOfClass:[NSDictionary class]]){
NSDictionary *dictionary=(NSDictionary*)json;
//取值
if([dictionary valueForKey:@"code"]){
NSNumber *code=dictionary[@"code"];
}
//赋值
[dictionary setValue:@"value" forKey:@"key"];
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: