Bancha Rojkittisakul
Bancha Rojkittisakul

Reputation: 166

Parse json array on iOS

I have the following JSON data:

[{"id":"value","first_name":"value","last_name":"value"},
 {"id":"value","first_name":"value","last_name":"value"},
 {"id":"value","first_name":"","last_name":""}]

Then I implement my code :

NSError *err;
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://abcd.com/index.php?r=WS/Employee"]];
NSData *dataFromUrl = [NSData dataWithContentsOfURL:url];
NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:dataFromUrl options: NSJSONReadingMutableContainers error:&err];

if (err)
    NSLog(@"JSONObjectWithData error: %@", err);

For which, I get the following error message:

JSONObjectWithData error: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x9c900f0 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

Please help me to get those data.

Upvotes: 0

Views: 436

Answers (4)

Bancha Rojkittisakul
Bancha Rojkittisakul

Reputation: 166

I fix this by replace request header in my PHP file from

echo "<meta charset=\"utf-8\">";

to

 ob_start();
 header('Content-type: application/json');

Upvotes: 1

BHASKAR
BHASKAR

Reputation: 1201

NSError *err;
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://abcd.com/index.php?r=WS/Employee"]];
NSData *dataFromUrl = [NSData dataWithContentsOfURL:url];
NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:dataFromUrl options:     NSJSONReadingMutableContainers error:&err];

if (err)
   NSLog(@"JSONObjectWithData error: %@", err);

Just Change your line

NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:dataFromUrl options:     NSJSONReadingMutableContainers error:&err];

with

NSJSONSerialization *jsonData = [NSJSONSerialization JSONObjectWithData:dataFromUrl options:     NSJSONReadingMutableContainers error:&err];
NSMutableArray *array = [NSMutableArray arrayWithArray:(NSArray *)jsonData];
NSLog(@"Success:%@", array);

Upvotes: 0

Shanthanu
Shanthanu

Reputation: 421

try this code....

NSURL * url =[NSURL URLWithString:getDataURL];
NSData * data=[NSData dataWithContentsOfURL:url];

json =[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

Upvotes: 0

Andrey Gagan
Andrey Gagan

Reputation: 1398

I think u should put something more in request header. Try convert NSData to NSString and look what is comming for you

Upvotes: 1

Related Questions