如何以正确的方式解析GET响应中的数据?



我试图解析来自web服务器的响应数据。我使用的是Xcode 4.2.

NSLog(@"Establishing connection...");
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:[NSURL URLWithString:@"example.com/test.php"]]; [request setHTTPMethod:@"GET"];
accept = @"Kokokoko";
NSLog(@"Adding value for HTTP Header");
[request addValue:accept forHTTPHeaderField: @"Accept"];
NSLog(@"Sending request...");
//send request & get response
returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSLog(@"Request sent");

然后我想使用returnData来解析JSON响应。应该是

["Test", "42", "OK"]

所以我试图使用NSDictionary和JSONValue和其他技巧,但我没有成功。也许这个问题有一个简单的解决办法?

如果您希望服务器返回这样的字符串:

["Test", "42", "OK"]

那么它的JSONValue将是NSArray(而不是NSDictionary)。试试这个:

NSString* responseString = [[[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding] autorelease];
NSLog(@"Response String: %@", responseString);
// Supposing that you are using SBJson, the parsing part may look like this:
//
NSArray* responseArray = [returnString JSONValue];
NSLog(@"Response Array: %@", responseArray);

最新更新