如何使用ios 4.3模拟器中的json从列表视图中的url获取数据

时间:2013-04-02 07:11:55

标签: ios objective-c ios4

我只是初学者在使用xcode 3.2的ios中,我想从url获取数据,我得到这样的JSON格式数据,如何显示Windows Live ID,Google with Image,loginUrl,logoutUr ..

JSON

0
Name : "Windows Live™ ID"

LoginUrl : ""

LogoutUrl : ""

ImageUrl : ""

EmailAddressSuffixes

1

Name : "Google"

LoginUrl : ""

LogoutUrl : ""

ImageUrl : ""

EmailAddressSuffixes

2

Name : "Yahoo!"

LoginUrl : ""

LogoutUrl : ""

ImageUrl : ""

EmailAddressSuffixes

我必须在.h文件和.m文件中写一下,有人可以帮助我吗?

提前致谢。

3 个答案:

答案 0 :(得分:0)

对于这一次尝试,请在tableview cellForRowAtIndex方法

中使用此方法

如果你想获得字典然后使用,

NSMutableDictionary *dict=[jsonArray objectAtIndex:indexPath.row];

如果你想获得字符串值,那么使用这个,

NSString * LoginUrl=[[jsonArray objectAtIndex:indexPath.row]valueForKey:@"LoginUrl"];

如果你想获得所有数据,那么使用一个for循环并保存这些数据。

答案 1 :(得分:0)

您可以使用NSURLConnection(或)Json libarary来解析从服务器接收的数据。

以下是使用NSURL连接解析JSON的示例代码:

在viewDidLoad中:

NSString *strConfirmChallenge = [URL string];

     strConfirmChallenge = [strConfirmChallenge stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"strConfirmChallenge=%@",strConfirmChallenge);

    NSURL *myURL = [NSURL URLWithString:strConfirmChallenge];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:60];

    NSURLConnection *theConnection =[[NSURLConnection alloc] initWithRequest:request delegate:self];


    //Delegate methods

    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
        responseData = [[NSMutableData alloc] init];
    }

    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
        [responseData appendData:data];
    }

    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
        //NSLog(@"Failed to get data");
        self.view.userInteractionEnabled = TRUE;
        UIAlertView *myalert = [[UIAlertView alloc]initWithTitle:@"Info" message:@"Service error" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [myalert show];
    }

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
        dispatch_async(kBgQue, ^{
            [self performSelectorOnMainThread:@selector(parseData:)
                                   withObject:responseData
                                waitUntilDone:YES];
        });
        self.view.userInteractionEnabled = TRUE;
    }



    //parsing data


    -(void)parseData:(NSData *)data{
         NSError *error;
            NSDictionary *data = [NSJSONSerialization JSONObjectWithData:data options:(0) error:&error];

            if(error){
                //NSLog(@"JSon Error %@",[error localizedDescription]);
                UIAlertView *myalert = [[UIAlertView alloc]initWithTitle:@"Info" message:@"Service error" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
                [myalert show];

            }else{
                NSDictionary *datDetails = (NSDictionary *) [data objectForKey:@"your key"];
        }
    }

答案 2 :(得分:0)

您可以使用SBJson来解析json。在项目中添加SBJson类,而不是使用此代码来解析json

-(void)WBCalled
{

    ExampleAppDataObject* theDataObject = [self theAppDataObject];

    //this code is used to send and retrive data from webservices
    NSString *post =@"";

    //NSLog(@"post is:%@",post);

    NSURL *url=[NSURL URLWithString:@""];

    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];

    NSError *error = [[NSError alloc] init];
    NSHTTPURLResponse *response = nil;
    NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    if ([response statusCode] >=200 && [response statusCode] <300)
    {
        NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
        // NSLog(@"Response ==> %@", responseData);

        SBJsonParser *jsonParser = [SBJsonParser new];   //here you are using sbjson library to parse json data
        NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
        NSLog(@"full jsonData : %@",jsonData);   //this dictionary contain all the data of your json response you can conver this data in NSString or NSArray according to your need

        NSString *message = (NSString *) [jsonData objectForKey:@"Message"];

        if (message.length !=0) {
            [self alertStatus:message :@"Status"];
        }


    } else {
        if (error) NSLog(@"Error: %@", error);
        [self alertStatus:@"Connection Failed" :@"Data Sending Failed!"];
    }

}
-(void) alertStatus:(NSString *)msg :(NSString *)title
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
                                                        message:msg
                                                       delegate:self
                                              cancelButtonTitle:@"Ok"
                                              otherButtonTitles:nil, nil];

    [alertView show];
}