如何通过iOS与json成员联系

时间:2013-07-09 13:19:17

标签: ios json parsing

我想从ios到.net .asmx网络服务,我可以使用以下代码:

NSString *urlString = @"http://www.****.com/Mobile.asmx/HelloWorld";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod: @"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];


NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned)
{
    //...handle the error
}
else
{
    NSString *retVal = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@", retVal);
    //...do something with the returned value


}

它返回干净的json {"hellom":"Hello World","hellom2":"HelloWorld2"},但我无法一个接触成员和值

我该怎么做?

1 个答案:

答案 0 :(得分:2)

您可以使用以下代码将JSON数据转换为对象...

NSData *jsonData = ... the data you got from the server

NSDictionary *object = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
然后

对象就像这样的NSDictionary ......

@{
    hellom : @"Hello World",
    hellom2: @"HelloWorld2"
}

然后,您可以像任何其他字典一样获取键和值。