user3871044
user3871044

Reputation: 21

Parse JSON in Objective-C

I am new to Objective-C, and JSON so I am confused on how to do this. I have looked up tutorials, and made sure my JSON is valid.

I have a SQL server database that I am trying to access by parsing JSON. I have checked to make sure my JSON is valid. Whenever I attempt to parse the JSON is Objective-C, however, it always returns null.

Here is my JSON:

[
{
    "ID": 1,
    "Username": "Cray",
    "Password": "fake",
    "Active": 0,
    "LastLogin": null
}
]

Here is my Objective-C code:

NSString *urlString = [NSString stringWithFormat:@"http://quacknasty.com/service.php"];

NSURL *url = [NSURL URLWithString:urlString];

NSData *data = [NSData dataWithContentsOfURL:url];

NSError *error;

NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

NSLog(@"test%@", json);

json always returns null when I do the NSLog

Upvotes: 0

Views: 195

Answers (2)

Julian F. Weinert
Julian F. Weinert

Reputation: 7560

Easy one: Open the URL in a browser. You will see that you don't have valid JSON:

Conneection established. 
[{"ID":1,"Username":"Cray","Password":"fake","Active":0,"LastLogin":null}]

You have to remove the echo of Connection established.\n

EDIT I: You have to use NSArray as root object, because the JSON string starts with []

EDIT II: Additionally you should set the correct HTTP Header fields as follows:

header('Content-Type: application/json; charset=utf-8');

Upvotes: 3

larva
larva

Reputation: 5148

Request to thi URL. Response is :

Conneection established. 
<br />[{"ID":1,"Username":"Cray","Password":"fake","Active":0,"LastLogin":null}]

It's not json format

Upvotes: 0

Related Questions