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

时间:2011-12-12 20:26:33

标签: iphone ios xcode json 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以及其他技巧,但我没有成功。也许这个问题有一个简单的解决方案?

1 个答案:

答案 0 :(得分:5)

如果您希望服务器返回类似的字符串:

["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);