0

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

3
  • 3
    You see that parm called "error". It has a purpose. if the result from NSJSONSerialization is nil, use NSLog to print out "error": NSLog(@"JSON error = %@", error); Commented Jul 24, 2014 at 1:06
  • I tried to access: quacknasty.com/service.php using Google Chrome browser, it returned an empty []. Are you sure your server returns some JSON? By the way, in the above code, your urlString is redundant, you can simply put [NSURL URLWithString:@"http://....."]; instead of [NSURL URLWithString:urlString]; since your urlString variable can be reduced to a string literal @"http://...."; Commented Jul 24, 2014 at 5:20
  • @Zhang: Technically [] is absolutely valid JSON! He did change his server code since yesterday, see my answer, there is the original API response. @user3871044: Did my answer solve your problems? Then please remember to accept :) Commented Jul 24, 2014 at 9:50

2 Answers 2

3

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'); 
Sign up to request clarification or add additional context in comments.

Comments

0

Request to thi URL. Response is :

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

It's not json format

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.