iOS 7:在以串联方式使用NSDictionary反序列化后获取JSON响应

时间:2014-09-23 13:14:18

标签: ios7 nsjsonserialization xcode5.1

从Web服务接收JSON响应后。我从Web服务获得此响应

{"d":"{\"Status\":0,\"Message\":\"Registered Successfully\",\"Token\":\"281fecff-2d44-4530-bc24-03558f1ebda1\",\"CurrentTimestamp\":\"23-09-2014 09:58:39 +05:30\",\"ValidUntilTimespan\":\"23-09-2014 09:58:39 +05:30\"}"}

我已经通过删除“d:”和“\”来反序列化这个字符串,使其成为有效的JSON  解析。

NSString *responseData = [[NSString alloc]initWithData:receivedData encoding:NSUTF8StringEncoding];
responseData = [responseData stringByReplacingOccurrencesOfString:@" " withString:@""];
responseData = [responseData stringByReplacingOccurrencesOfString:@"\\" withString:@""];
responseData = [responseData stringByReplacingOccurrencesOfString:@"\"d\":" withString:@""];
responseData = [responseData substringToIndex:[responseData length] - 2];
responseData = [responseData substringWithRange:NSMakeRange(2, [responseData length]-2)];

NSLog(@"Reponse data %@",responseData);
NSData *jsonData = [responseData dataUsingEncoding:NSUTF8StringEncoding];
NSError *errorJson=nil;
NSDictionary *myDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&errorJson];
NSLog(@"Final %@",myDictionary);

NSString *valueMessage = [myDictionary objectForKey:KeyMessage];
NSString *valueStatus = [myDictionary objectForKey:KeyStatus];
NSString *valueCurrentTimestamp = [myDictionary objectForKey:KeyCurrentTimestamp];
NSString *valueToken = [myDictionary objectForKey:KeyToken];
NSString *valueValidUntillTimepstamp = [myDictionary objectForKey:KeyValidUntillTimepstamp];
    //values
NSLog(@"Message = %@",valueMessage);
NSLog(@"Status = %@",valueStatus);
NSLog(@"currenttimestamp= %@",valueCurrentTimestamp);
NSLog(@"token= %@",valueToken);
NSLog(@"validuntiltimespan= %@",valueValidUntillTimepstamp);

这是我的日志结果:

014-09-23 10:03:13.885 Sbits_Journal[1015:60b] Response data   {"Status":0,"Message":"RegisteredSuccessfully","Token":"281fecff-2d44-4530-bc24-0   3558f1ebda1","CurrentTimestamp":"23-09-201409:58:39+05:30","ValidUntilTimespan":"23-09-  201409:58:39+05:30"}
2014-09-23 10:03:13.886 Sbits_Journal[1015:60b] Final {
CurrentTimestamp = "23-09-201409:58:39+05:30";
Message = RegisteredSuccessfully;
Status = 0;
Token = "281fecff-2d44-4530-bc24-03558f1ebda1";
ValidUntilTimespan = "23-09-201409:58:39+05:30";
}

但是我以串联的方式获得字符串响应“RegisteredSuccessfully”喜欢这个 但我想获取此字符串并显示警告由于获取此类字符串,我无法在警报中显示“已成功注册”。 这是我解析的正确方法还是还有另一种消毒方式? 在此先感谢。

1 个答案:

答案 0 :(得分:1)

我逐行调试后找出了问题

responseData = [responseData stringByReplacingOccurrencesOfString:@" " withString:@""];

由于这个线路空间被连接所以我只是评论上面的线并再次运行。 我知道这是一个很小的问题,但也许可以帮助某人,所以我回答了我自己的问题。