我正在尝试存储从以下请求中获取的JSON中的JSON …
NSURL *URL = [NSURL URLWithString:@"http://www.demo.com/server/rest/login?username=admin&password=123"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL]; [request setHTTPMethod:@"GET"]; NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) { if (error) { // Handle error... return; } if ([response isKindOfClass:[NSHTTPURLResponse class]]) { NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]); NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]); } NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"Response Body:\n%@\n", body); }]; [task resume];
得到的JSON从获得 的身体 是下面的,正如你可以看到有是JSON内的JSON,我怎么能存储 的是 JSON在 NSDictionary中 ,你可以看到,JSON是引号之间。
[ { tag: "login", status: true, data: " { "userID":1, "name":"John", "lastName":"Titor", "username":"jtitor01", "userEmail":"jtitor01@gmail.com", "age":28, } " } ]
实际上,您拥有的是:经典JSON,其中有一个字符串“代表” JSON。
因此,由于我们可以这样做: NSData <=> NSString NSArray / NSDictionary <=> JSON NSData 我们只需要根据我们拥有的数据类型在它们之间进行切换。
NSArray *topLevelJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; NSString *lowLevelString = [[topLevelJSON firstObject] objectForKey:@"data"]; NSData *lowLevelData = [lowLevelString dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary *final = [NSJSONSerialization JSONObjectWithData:lowLevelData options:0 error:nil];