我正在尝试使用 nsdictionary 获取这些数据。我的数据如下所示:
{
"Id": 1,
"Items": [
{
"Id": 1,
"CorrectAnswer": "sample string 3",
"Difficulty": 4,
"CategoryId": 5,
"CategoryName": "sample string 6",
"AccountId": 7
},
{
"Id": 1,
"PicUrl": "sample string 2",
"CorrectAnswer": "sample string 3",
"Difficulty": 4,
"CategoryId": 5,
"CategoryName": "sample string 6",
"AccountId": 7
}
"StartTime": "2013-10-07T00:24:22.0048045+00:00"
}
这是尝试过的:
- (IBAction)play:(id)sender {
[self performSegueWithIdentifier:@"playSegue" sender:self];
NSString *GameId;
NSNumber *ID;
NSURL *PictureURL;
NSString *ans1;
NSString *ans2;
NSString *ans3;
NSString *ans4;
NSArray *answers = [[NSArray alloc]initWithObjects:ans1,ans2,ans3,ans4, nil];
NSString *correctAnswer;
NSString *difficulty;
NSString *categoryID;
NSString *categoryName;
NSNumber *accountID;
NSArray *items = [[NSArray alloc]initWithObjects:ID,PictureURL,answers,correctAnswer,categoryID,categoryName,accountID, nil];
NSDictionary *result = [self requestWithPath:[NSString stringWithFormat:@"someurlhere"] Method:@"GET"
Data:[NSDictionary dictionaryWithObjectsAndKeys:
GameId,@"GameId",
items, @"Items",
nil]
Parse:YES];
NSLog(@"the result is %@",result);
}
-(NSDictionary *)requestWithPath:(NSString *)path
Method:(NSString *)requestMethod
Data:(NSDictionary *)requestData
Parse:(BOOL)parse
{
if(path) NSLog(@"%@", path);
if(requestData) NSLog(@"%@", requestData);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[[NSString stringWithFormat:@"%@", path] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
[request setHTTPMethod:requestMethod.uppercaseString];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
if(requestData && [NSJSONSerialization isValidJSONObject:requestData])
{
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:requestData options:0 error:&error];
[request setHTTPBody:data];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [data length]] forHTTPHeaderField:@"Content-Length"];
}
NSURLResponse *response = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL];
if(responseData)
NSLog(@"%@", [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]);
if(parse && responseData)
{
NSError *serializationError = nil;
return [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&serializationError];
}
else if (responseData)
return @{@"string": [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]};
return nil;
}
控制台结果
2013-10-06 19:01:16.477 FlickRest[41610:a0b] someurlhere
2013-10-06 19:01:16.478 FlickRest[41610:a0b] {
}
2013-10-06 19:01:17.186 FlickRest[41610:a0b] the result is (null)
我的问题
除了没有得到我想要的结果之外,我相信我没有以正确的方式做到这一点。有人可以指出我的错误或建议一种如何正确转换 JSON 数据的方法吗?谢谢你。