如何从以下代码中提取值?

时间:2013-07-19 14:16:45

标签: iphone ios objective-c nsarray

如何从以下代码中仅提取“令牌”值?我希望将此值保存为字符串。

meta是一个数组吗?如果是这样,我如何从“令牌”值中提取数据?

感谢您的帮助

 NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];


Response ==> {"meta":[],"data":{"token":"IVZ2ciRkbVtDLUl3YmhwOTkyXzpRR1M3LUUsRiElfWF6T3I6dCxsRWg6di1XcyR6OTUzZHhVazdLTEJ7blU5O258d2xRTXg0VUxwQXBlNHRSOXd2VXZ1aG1RfFhQQjJsSkkoc2IuOTFyYkYodyhAe2RldXR1aDF3RClXWyhoMiU="}}
2013-07-19 15:10:23.139 appName [11190:907] {
    data =     {
        token = "IVZ2ciRkbVtDLUl3YmhwOTkyXzpRR1M3LUUsRiElfWF6T3I6dCxsRWg6di1XcyR6OTUzZHhVazdLTEJ7blU5O258d2xRTXg0VUxwQXBlNHRSOXd2VXZ1aG1RfFhQQjJsSkkoc2IuOTFyYkYodyhAe2RldXR1aDF3RClXWyhoMiU=";
    };
    meta =     (
    );
}

3 个答案:

答案 0 :(得分:2)

我认为数据是JSON格式的。在这种情况下,这应该有用。

NSError *error = nil;
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:urlData options:0 error:&error];
NSString *token = [[responseDict objectForKey:@"data"] objectForKey:@"token"];

答案 1 :(得分:1)

在您的情况下,metaArraydataDictionary。如果您的响应在JSON中格式正确,那么您可以使用以下示例代码获取TokenStringmetaArray

示例代码:

NSData *data = [NSData dataWithContentsOfURL:yourURL];
NSError* error = nil;
NSDictionary* responseDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSString *token = [[responseDict objectForKey:@"data"] objectForKey:@"token"];
NSArray *meta = [responseDict objectForKey:@"meta"];
NSLog(@"\ntoken :: %@\nmeta :: %@",token,meta);

PS: 要了解有关JSON响应的更多信息,请查看此 Answer

答案 2 :(得分:1)

我只是这样做:

NSData *responseData = [NSData dataWithContentsOfURL:yourURL];
NSString *token = [NSJSONSerialization JSONObjectWithData:responseData
  options:kNilOptions error:NULL][@"data"][@"token"];

如果有任何错误,它将是nil