ios中将单个字典转换成json格式以及json格式的转换成字典解析

    
    //1.这段代码是将字典封装数据。
    NSMutableDictionary *dict  = [[NSMutableDictionary alloc]init];
    [dict setValue:@"谢飞" forKey:@"name"];
    [dict setValue:@"[email protected]" forKey:@"email"];
    [dict setValue:@"ios工程师" forKey:@"profession"];

    //2.字典序列化,变成json字符串
    NSData *dictData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonString = [[NSString alloc]initWithData:dictData encoding:NSUTF8StringEncoding];
    
    //3.将json字符串再次转换成单个字典字段。
    NSData* xmlData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *perDict = [NSJSONSerialization JSONObjectWithData:xmlData options:(NSJSONReadingMutableLeaves) error:nil];
    NSString *name2 = [perDict objectForKey:@"name"];
    NSLog(@"姓名是:%@",name2);

你可能感兴趣的:(ios)