您的位置:首页 > Web前端 > JavaScript

Json字符串转换为NSDictionary

2015-10-29 21:28 645 查看
首先看字符串

{

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];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: