Search code examples
iosobjective-cnsdictionarynsjsonserialization

Unable to read data after NSJSONSerialization


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

    }

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