1. 程式人生 > >IOS開發學習27 ObjectC 自帶json解析方法的使用

IOS開發學習27 ObjectC 自帶json解析方法的使用

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"];
    }