iOS如何在检索Web响应数据后从JSON检索值

时间:2015-12-30 03:59:18

标签: ios objective-c arrays json rest

我正在尝试发出nsurl请求并设法检索Web响应数据。问题是我想从JSON列表中检索特定参数。 我要检索的参数是“id”,并在标签中显示。

这是我用于建立连接的viewDIDLoad:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.


    feeds = [[NSMutableArray alloc] init];

     NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://coolsoft.mousy.com/v1/messi/reports"]];

    // Prepare the variables for the JSON response


    // Create a mutable copy of the immutable request and add more headers
    NSMutableURLRequest *mutableRequest = [request mutableCopy];

    [mutableRequest addValue:@"application/json" forHTTPHeaderField:@"request"];
    // Make synchronous request

    request = [mutableRequest copy];

    // Log the output to make sure our new headers are there
    NSLog(@"%@", request.allHTTPHeaderFields);




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

    if(connection)
    {
        _webResponseData = [NSMutableData data] ;


    }
    else
    {
        NSLog(@"Connection is NULL");
    }

}

他是我的connectionDidFinishLoading方法:

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {

    NSLog(@"Received %lu Bytes", (unsigned long)[_webResponseData length]);
//    NSString *theXML = [[NSString alloc] initWithBytes:
//                        [_webResponseData mutableBytes] length:[_webResponseData length] encoding:NSUTF8StringEncoding];

    // convert to JSON
    NSError *myError = nil;
    NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.webResponseData options:NSJSONReadingMutableLeaves error:&myError];
    NSString *icon;
    // show all values
    for(id key in res) {

        id value = [res objectForKey:key];

        NSString *keyAsString = (NSString *)key;
        NSString *valueAsString = (NSString *)value;

        NSLog(@"key: %@", keyAsString);
        NSLog(@"value: %@", valueAsString);
    }

    // extract specific value...
    NSArray *results = [res objectForKey:@"id"];

    for (NSDictionary *result in results) {
      icon   = [result objectForKey:@"id"];
        NSLog(@"icon: %@", icon);

    }

    output.text = icon;


    output = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 200, 100)]; //adjust label size and position as needed
    output.font = [UIFont fontWithName:@"BradleyHandITCTT-Bold" size: 23.0];
    output.textColor = [UIColor whiteColor];
    output.textAlignment = NSTextAlignmentCenter;
    output.numberOfLines = 0; //note: I said number of lines need to be 2
    output.backgroundColor = [UIColor clearColor];
    output.adjustsFontSizeToFitWidth = YES;
    output.tag = 100;
}

当我NSLOG res res词典时输出:

( { date = "2014-08-28T00:00:00Z"; id = 300005; title = "July 2014 USAA Phishing Campaign Uses KeNiHaCk Exploit"; uri = "/v1/joker/reports/300005"; }, { date = "2014-12-16T20:46:29Z"; id = 300062; title = "Two-Year Chinese Spearphishing Campaign Largely Targeted Japanese Aerospace and Energy Industries"; uri = "/v1/joker/reports/300062"; },

这是我的错误消息:

-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x136713360
2015-12-30 11:58:17.692 FYP_IOS_APP[817:323807] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x136713360'

2 个答案:

答案 0 :(得分:1)

你的JSON回复是{" id":300005," title":" pink"," date":" 2014-08-28T00:00:00Z"" URI":" www.hipster.com/hip"}}

所以,您可以使用like,lblName.text = [res valueForKey:@"id"];

答案 1 :(得分:0)

您的json解析没问题,它为您提供了NSSictionary的JSON 但是你需要对NSDictionary对象进行一些小改动,如下所示。

请参阅以下代码&它可能会帮助你

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
    //{"id":300005, "title":"pink", "date":"2014-08-28T00:00:00Z", "uri":"www.hipster.com/hip"}
    NSLog(@"Received %lu Bytes", (unsigned long)[_webResponseData length]);

    // convert to JSON
    NSError *myError = nil;
    NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.webResponseData options:NSJSONReadingMutableLeaves error:&myError];
    NSString *icon;

    // show all values
    for(id key in [res allKeys]) {
        NSLog(@"key: %@", key);
        NSLog(@"value: %@", [res objectForKey:key]);
    }

    // extract specific value...
    icon = [res valueForKey:@"id"];
    NSLog(@"icon: %@", icon);

    output.text = icon;

    output = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 200, 100)]; //adjust label size and position as needed
    output.font = [UIFont fontWithName:@"BradleyHandITCTT-Bold" size: 23.0];
    output.textColor = [UIColor whiteColor];
    output.textAlignment = NSTextAlignmentCenter;
    output.numberOfLines = 0; //note: I said number of lines need to be 2
    output.backgroundColor = [UIColor clearColor];
    output.adjustsFontSizeToFitWidth = YES;
    output.tag = 100;
}

<强>更新

// convert to JSON
NSError *myError = nil;
NSArray *res = [NSJSONSerialization JSONObjectWithData:self.webResponseData options:NSJSONReadingMutableLeaves error:&myError];

// show all values
for(NSDictionary *dic in res) {
    for(NSString *key in [dic allKeys]) {
        NSLog(@"key: %@", key);
        NSLog(@"value: %@", [dic objectForKey:key]);
    }
}