我收到了JSON回复
(
{
Response = success;
UserId = 287;
}
)
我尝试使用以下代码解析用户ID
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:receivedData options:0 error:&e];
NSLog(@"%@", dataDictionary);
NSString *useridstring=[dataDictionary valueForKey:@"UserId"];
但我获得了用户ID ( 287 )
。
请建议我如何获得没有paraparentheses的用户ID
答案 0 :(得分:1)
您需要从JSON响应中获取整数值。
int userid = [[dataDictionary valueForKey:@"UserId"] intValue];
如果在整数响应中也得到括号,那么回复JSON
响应就会出现问题。对于解决方法,您可以使用 -
NSString *useridstring=[dataDictionary valueForKey:@"UserId"];
int userid = [[useridstring substringWithRange:NSMakeRange(1, useridstring.length - 2)] intValue]
编辑 -
你得到一个响应数组,为此你必须使用 -
int userid = [[dataDictionary valueForKey:@"UserId"] firstObject];
答案 1 :(得分:1)
您的回复不是字典,而是一个数组。所以你的代码应该是这样的:
NSArray *dataArray = [NSJSONSerialization JSONObjectWithData:receivedData options:0 error:&e];
NSLog(@"%@", dataArray);
NSDictionary *dataDictionary = dataArray[0]; //Same as objectAtIndex:
NSString *userIDString = dataDictionary[@"UserID"]; //Same as objectForKey:
//If you're still getting parens try this:
//int userIDInt = [dataDictionary[@"UserID"] intValue];