zac zac - 1 month ago 14
iOS Question

iOS How to retrieve value from JSON after retrieving web response data

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'

Answer

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]);
    }
}