-4

I am trying to make a nsurl request and manage to retrieve the web response data out. The problem is i want to retrieve the specific parameter from the JSON list. The parameter i want to retrieve is "id" and display it out in a label.

Here is my viewDIDLoad for establishing the connection:

- (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");
    }

}

His is my connectionDidFinishLoading method:

-(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;
}

Here is output when i NSLOG the res dictionary:

( { 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"; },

Here is my error message:

-[__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'
zac
  • 83
  • 12
  • 3
    This have been asked for a thousand times, u have to cast your json to dictionary then retrieve the data with key-value, please try google before asking – Tj3n Dec 30 '15 at 04:07
  • NSArray *results = [res objectForKey:@"id"]; this is wrong. You are getting is as string not an array. – Ekta Padaliya Dec 30 '15 at 04:09
  • Possible duplicate of [JSON parsing using NSJSONSerialization in iOS](http://stackoverflow.com/questions/20399087/json-parsing-using-nsjsonserialization-in-ios) – Ashish Kakkad Dec 30 '15 at 04:12

2 Answers2

1

Your JSON response is {"id":300005,"title":"pink","date":"2014-08-28T00:00:00Z","uri":"www.hipster.com/hip"}}

So, You can use like, lblName.text = [res valueForKey:@"id"];

Keyur Hirani
  • 1,607
  • 14
  • 22
0

Your json parsing is OK and it gives you JSON to NSDictionary
but you need some minor changes in pasing that NSDictionary object as below.

see this below code & It may help you

-(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;
}

update

// 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]);
    }
}
Haresh Ghatala
  • 1,996
  • 17
  • 25
  • -[__NSCFArray allKeys]: unrecognized selector sent to instance 0x13eecdea0 2015-12-30 13:46:33.679 FYP_IOS_APP[864:338722] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray allKeys]: unrecognized selector sent to instance 0x13eecdea0' – zac Dec 30 '15 at 05:47
  • when i log out the response for res it shows this: ( { 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"; }, – zac Dec 30 '15 at 05:49
  • @zac have you debug the code? & does app gives error at the start of the loop? because it seems some other issue or you may be you are getting `NSArray` in your response and parsing it as `NSDictionary` – Haresh Ghatala Dec 31 '15 at 09:16
  • @zac first check your `res` class type by `NSLog(@"%@",[res class])` if it is `NSArray Type` then use `NSArray *res` insted `NSDictionary *res` and parse your data accordingly. – Haresh Ghatala Dec 31 '15 at 09:19