如何解析从Webservice响应中收到的JSON响应

时间:2014-09-11 14:44:06

标签: json ios7 nsjsonserialization

我从WebService获得此响应

{"d":"{"token":"b502645e-837f-4237-a6ff-d4323f2799dd","timestamp":"09/11/20147:46:43PM"}"}

我想解析这个字符串,以便我可以获得如下输出:    token = b502645e-837f-4237-a6ff-d4323f2799dd    时间戳= 09/11/20147:46:43PM  这样我就可以将它存储到数据库中。

这是我的代码

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// The request is complete and data has been received
// You can parse the stuff in your instance variable now
/*
NSError *errorJson=nil;
NSString* OuterDict = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&errorJson];
NSLog(@"Outer Dictionary %@",OuterDict);
 */
NSString *responseData = [[NSString alloc]initWithData:receivedData encoding:NSUTF8StringEncoding];

responseData = [responseData stringByReplacingOccurrencesOfString:@" " withString:@""];
responseData = [responseData stringByReplacingOccurrencesOfString:@"\\" withString:@""];
//NSString* encodedString = [responseData stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//NSLog(@"%@",encodedString);
NSLog(@"Reponse data %@",responseData);
NSError *errorJson=nil;

NSData *jsonData = [responseData dataUsingEncoding:NSUTF8StringEncoding];
jsonData = [jsonData subdataWithRange:NSMakeRange(0, [jsonData length] - 1)];
NSDictionary* OuterDict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&errorJson];
NSLog(@"Outer Dict %@",OuterDict);

}

我收到null作为输出: Outer Dict (null)

任何人都可以帮我这个。 在此先感谢。

1 个答案:

答案 0 :(得分:1)

在方法顶部使用以下代码段。它将解析您的JSON数据并返回字典。您可以根据需要对Dictionary执行任何操作。

NSDictionary *dictResponse = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingAllowFragments error:&err];
NSLog(@"Response : %@", dictResponse);

快乐编码:)