Question

I am getting a json array from the server. The jsonOutput object shows 2 objects correctly. But am unable to display or extract the data. Could some one help me out. I tried the following way :

 for (id key in jsonOutput) {
          NSLog(@"key: %@, value: %@", key, [jsonOutput objectForKey:key]);
        }

declaration : NSDictionary *jsonOutput;

actualmethods :

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

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


       // if ([connection isEquals:connect1]){
            // this is request urlConnectionRecsender
       // }
    }

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

    jsonOutput= [NSJSONSerialization JSONObjectWithData:data options:nil error:nil];


    for (id key in jsonOutput) {
          NSLog(@"key: %@, value: %@", key, [jsonOutput objectForKey:key]);
        }

    }
Was it helpful?

Solution

Try this

NSError *error;

jsonOutput= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

if(error) 
    NSLog(@"%@",error.description);

If you don't know what is response type, then it is always a good practice to check respone type first

id responseObj = [NSJSONSerialization
                      JSONObjectWithData:data
                      options:kNilOptions
                      error:&error];
    if ([responseObj isKindOfClass:[NSArray class]]) {
       //Your response is a array
    }
    else if([responseObj isKindOfClass:[NSDictionary class]]) {
        //Your response is a dictionary
    }

Your array contains NSDictionary

{ cropName = corn; cropOrderId = 1; cropPrice = 100; "farmer_id" = 1; orderStatus = pending; quantity = 5; } 

use this code to get value

for(NSDictionary*dict in jsonObject) {

    NSArray *allKeysarr = [dic allKeys];

    for(NSString *key in allKeysarr) {

         NSLog(@"%@",[dic valueForKey:key]);
     }

}

OTHER TIPS

first use error handling:

NSError *error;
jsonOutput= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (error) NSLog(@"error: %@",error.description);

then access values with:

NSString *value1 = [jsonOutput objectForKey:@"YOUR_KEY1"];

NSData *xmlData = [NSData dataWithContentsOfFile:xmlPath];

NSError *jsonError = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:xmlData options:kNilOptions error:&jsonError];

if ([jsonObject isKindOfClass:[NSArray class]]) {
    NSLog(@"its an array!");
    NSArray *jsonArray = (NSArray *)jsonObject;
    NSLog(@"jsonArray - %@",jsonArray);
}
else {
    NSLog(@"its probably a dictionary");
    NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;
    NSLog(@"jsonDictionary - %@",jsonDictionary);
}

Try this once

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top