Json字符串转换为NSDictionary

来源:互联网 发布:js农历插件 编辑:程序博客网 时间:2024/04/29 15:26

首先看字符串

{    res =     (        "Teacher Site",        "http://xxx.com/"    );}

我们需要将字符串变换称如下字符串才可以转换成功


{    "res" :[        "Homework",        "http://xxx.com/"    ]}

具体代码如下:

        NSString *resTmpStr=[resStr stringByReplacingOccurrencesOfString:@"res =     (" withString:@"\"res\":["];        resTmpStr=[resTmpStr stringByReplacingOccurrencesOfString:@");" withString:@"]"];        resTmpStr=[resTmpStr stringByReplacingOccurrencesOfString:@"Homework" withString:@"\"Homework\""];        NSData* data1 = [resTmpStr dataUsingEncoding:NSUTF8StringEncoding];        __autoreleasing NSError* error = nil;        NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data1 options:kNilOptions error:&error];        if (error != nil) {            NSLog(@"convert error");            continue;        };                NSArray *data = [res objectForKey:@"res"];        if (data != nil) {            if (result == nil) {                result = [[NSMutableArray alloc] init];            }            Resource *tmp = [[Resource alloc] init];            tmp.schoolName = data[0];            tmp.url = data[1];            if (data.count > 2) {                tmp.userName = data[2];                tmp.password = data[3];            }            [result addObject:tmp];        }





0 0
原创粉丝点击