Divya
Divya

Reputation: 87

Cannot fetch values from Json with no key in ios

[
    {
        "Id": 52,
        "Name": "name1",
        "author": "john"
    },
    {
        "Id": 53,
        "Name": "name2",
        "author": "jacob"
    },
    {
        "Id": 54,
        "Name": "name3",
        "author": "jobin"
    }
]

I used the following code to fetch and parse this json array with no main key

SBJsonParser *parser1 = [[SBJsonParser alloc] init];
   NSURLRequest *request1 = [NSURLRequest requestWithURL:[NSURL URLWithString:str2]];
    // Perform request and get JSON back as a NSData object
    NSData *response1 = [NSURLConnection sendSynchronousRequest:request1 returningResponse:nil error:nil];
    NSError *error;
   NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:response1 options:kNilOptions error:&error];

but i am getting the following exception

data parameter is nil 

this exception is occuring at this code

NSData *response1 = [NSURLConnection sendSynchronousRequest:request1 returningResponse:nil error:nil];

How to iterate the id value?

Upvotes: 0

Views: 293

Answers (3)

Giwan
Giwan

Reputation: 1590

The return value from sendSynchronousRequest is void. So it makes sense that the data parameter is nil.

+ (void)sendAsynchronousRequest:(NSURLRequest *)request
                      queue:(NSOperationQueue *)queue
          completionHandler:(void (^)(NSURLResponse *response,
                                      NSData *data,
                                      NSError *connectionError))handler

The data value you're expecting is provided in the block. That's where you want to extract the NSArray and do something with it.

In my current project, I'm not using synchronousRequest but doing something similar. Maybe that helps you.

    NSError *error;
    // Read the given JSON file from the server
    NSData *filedata = [NSData dataWithContentsOfURL:url options:kNilOptions error:&error];

    if (filedata)
    {
        // Read the returned NSData from the server to an NSDictionary object
        // Essentially this is the bookstore in NSDictionary format.
        NSArray *bookStore = [NSJSONSerialization JSONObjectWithData:filedata options:kNilOptions error:&error];

    }

Upvotes: 0

Halpo
Halpo

Reputation: 3134

You have an array of JSON files here, so i would:

NSArray *jsonArray = ; //your JSON

for (NSDictionary *dict in jsonArray) {
    NSInteger number = [dict[@"Id"] intValue];
    NSString *name = dict[@"Name"];
    NSString *author = dict[@"author"];
}

Upvotes: 1

Thanks
Thanks

Reputation: 13

What you given is perfect it is working for me try check your API And you did not use the SBJson also try print the NSLog("%@",jsonArray);

Upvotes: 0

Related Questions