JSON returning null - iphone

I'm having a bit of trouble parsing some returned JSON. I'm fairly new to working with JSON. I'm trying to get the company name from the first JSON array element. I have a feeling that I'm confusing the use of NSMutabeArray and NSMutableDictionary. What I get is null. Any idea what I'm doing wrong?
NSString *url = #"http://www.google.com/finance/info?infotype=infoquoteall&q=C,JPM,AIG,AAPL";
NSData* data = [NSData dataWithContentsOfURL:
[NSURL URLWithString: url]];
//parse out the json data
NSError* error;
NSMutableArray* json = [NSJSONSerialization
JSONObjectWithData:data //1
options:kNilOptions
error:&error];
NSString* companyName = [[json objectAtIndex:0] objectForKey:#"name"] ; //Where I need some help
NSLog(#"we got %#", companyName);

Load that url in your browser. Looks like google is prefixing the JSON with //. I think NSJSONSerialization is tripping on that. Try this
NSRange range = NSMakeRange(2, [data length] - 3);
NSData *noPrefix = [data subdataWithRange:range];
Then send that to the parser.

You put in an error object, but you never looked at it. If you had, you would see that the data is corrupted:
Error Domain = NSCocoaErrorDomain Code = 3840 "The data couldn’t be read because it has been corrupted." (Invalid value around character 1.) UserInfo = 0x10030a8f0 { NSDebugDescription = Invalid value around character 1. }
I changed the value of the options parameter to see this error. I have
NSMutableArray* json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers |NSJSONReadingAllowFragments error:&error];

Related

How to separate JSON response in iphone

I have an application in which I am having a json response like this.
{"success":"true","message":"You have logged in","pserial":"1"} and I am separating with ":".
And I am getting data like this pSerial:"1"} but I want only 1 value.
NSURL *url = [NSURL URLWithString:strUrl];
NSData *respData = [NSData dataWithContentsOfURL:url];
NSString *strResp = [[NSString alloc]initWithData:respData encoding:NSUTF8StringEncoding];
NSString *approvalString = [[strResp componentsSeparatedByString:#":"] objectAtIndex:3];
NSLog(#"pSerial:%#",approvalString);
for Example :
SBJsonParser *jsonPar = [[SBJsonParser alloc] init];
NSError *error = nil;
NSArray *jsonObj = [jsonPar objectWithString:jsonString error:&error];
id jsonObj = [jsonPar objectWithString:jsonString error:&error];
if ([jsonObj isKindOfClass:[NSDictionary class]])
// treat as a dictionary, or reassign to a dictionary ivar
else if ([jsonObj isKindOfClass:[NSArray class]])
// treat as an array or reassign to an array ivar.
Then get the value :
NSMutableArrary *userMutArr = [NSMutableArray array];
for (NSDictionary *dict in jsonObj)
{
User *userObj = [[[User alloc] init] autorelease];
[userObj setFirstName:[dict objectForKey:#"firstName"]];
[userObj setLastName:[dict objectForKey:#"lastName"]];
[userObj setAge:[[dict objectForKey:#"age"] intValue]];
[userObj setAddress:[dict objectForKey:#"address"]];
[userObj setPhoneNumbers:[dict objectForKey:#"phoneNumber"]];
[userMutArr addObject:userObj];
}
Hope you will understand. and read some Documents. it will help you.
It looks like you are in need of JSON Parsing. Here, what you want is JSON Parsing, not separating data from the JSON Response. JSON is the format of the data in which data is formatted in Key-Value pairs. You can fetch the "Value" of any object using the "Key".
Your first two lines are correct.
NSURL *url = [NSURL URLWithString:strUrl];
NSData *respData = [NSData dataWithContentsOfURL:url];
Now, you can parse JSON Response like this :
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:respData options:kNilOptions error:&error];
NSString *pSerial = [json objectForKey:#"pserial"];
This will give you the value of "pserial" from your response. Similarly, you can get the values for "success" and "message". You can check it using this line :
NSLog(#"pserial :: %#",pserial);
You need to parse the JSON Response String, you can use any JSON parser like:
https://github.com/stig/json-framework/
And in your code do:
NSString *strResp = [[NSString alloc]initWithData:respData encoding:NSUTF8StringEncoding];
NSDictionary *ResponseDictionary = [strResp JSONValue];
NSString * pSerial = (NSString*)[ResponseDictionary objectForKey:#"pserial"];
Dont separation by ":" just use JSONValue your response is like
// {"success":"true","message":"You have logged in","pserial":"1"}
// with SBJsonParser parse your object like this
NSDictionary *responseJson = [YOUR-OBJECT JSONValue];
Note: dont forget to add Json header file
Its better you use any OpenSource Json Parser
Here is a stack post Comparison of different Json Parser for iOS

NSJSONSerialization returning nil

{"User":{"id":"42","name":"martin"}}
Converting my NSData to NSString returns this JSON which seems completely valid, however the method:
[NSJSONSerialization isValidJSONObject:data]
is saying this is not a valid JSON object.
Could anyone point out a mistake I have made or think of a reason why this is happening?
I bet there is a non-printable character in your string for example, making the data invalid.
Declare an NSError* error variable then call [NSJSONSerialization JSONObjectWithData:data options:0 error:&error] method to try to convert the JSON: obviously if your data is considered invalid, it will return nil, but at least you will have the description of what's wrong in the NSError* error variable after that.
NSData* data = ... // your data
NSError* error = nil; // Declare a variable to hold the error upon return
id obj = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; // Try to convert your data
NSLog(#"obj: %# ; error: %#", error); // Log the decoded object, and the error if any

How to Parse this JSON in Objective-C

I'm new in iPhone programming.
I have to parse this data in JSON in Objective-C.
{"success":1,"check":[{"ChkKey":"2","ChkDeb":"Connection 1","ChkSSID":"Netgear-1111","ChkIP":"192.168.2.103","ChkBlk":"0"}]}
I follow the example for parsing data with Json. But this JSON is so different.
It is composed by two Array.
How can i proceed?
Thanks - A.b.
How about trying something like this ...
//JSON string
NSString *jsonString = #"{\"success\":1,\"check\":[{\"ChkKey\":\"2\",\"ChkDeb\":\"Connection 1\",\"ChkSSID\":\"Netgear-1111\",\"ChkIP\":\"192.168.2.103\",\"ChkBlk\":\"0\"}]}";
//Parse JSON string into an NSDictionary
NSError *e = [[NSError alloc] init];
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&e];
//Output the value of success
NSLog(#"Success:%#", [jsonData objectForKey:#"success"]);
//Get data in the check array
NSDictionary *checkData = [[jsonData objectForKey:#"check"] objectAtIndex:0];
//Output the value of ChkSSID
NSLog(#"ChkSSID:%#", [checkData objectForKey:#"ChkSSID"]);

Removing // from NSMutableArray

When I NSLog the contents of an NSMutableArray I get null. I believe I know what the issue is.
I'm having a bit of trouble trying to figure out how to remove "//" at the beginning of this JSON output. If you load http://www.google.com/finance/info?infotype=infoquoteall&q=AAPL,C into your browser you'll see the "//" at the beginning. I believe that the "//" is what is causing the array to return null. How could I go about removing the two dashes? Below is I have what I've done thus far...
NSString *url = #"http://www.google.com/finance/info?infotype=infoquoteall&q=C,JPM,AIG,AAPL";
NSData* data = [NSData dataWithContentsOfURL:
[NSURL URLWithString: url]];
//parse out the json data
NSError* error;
NSMutableArray* json = [NSJSONSerialization
JSONObjectWithData:data //1
options:kNilOptions
error:&error];
NSLog(#"json is %#", json); //returns "json is (null)"
You can try this:
NSData *newData = [data subdataWithRange:NSMakeRange(4, [data length] -4)];
This gets rid of the first four characters. There was a control character the two slashes and a space before the first "[", and this gets rid of those. I tried this but the data still had a flaw in it further on.

Parse json in objective-c for my iphone app

i have a problem parsing my json data for my iPhone app, I am new to objective-C. I need to parse the json and get the values to proceed. Please help. This is my JSON data:
[{"projId":"5","projName":"AdtvWorld","projImg":"AdtvWorld.png","newFeedCount":"0"},{"projId":"1","projName":"Colabus","projImg":"Colabus.png","newFeedCount":"0"},{"projId":"38","projName":"Colabus Android","projImg":"ColabusIcon.jpg","newFeedCount":"0"},{"projId":"25","projName":"Colabus Internal Development","projImg":"icon.png","newFeedCount":"0"},{"projId":"26","projName":"Email Reply Test","projImg":"","newFeedCount":"0"},{"projId":"7","projName":"PLUS","projImg":"7plusSW.png","newFeedCount":"0"},{"projId":"8","projName":"Stridus Gmail Project","projImg":"scr4.png","newFeedCount":"0"}]
On iOS 5 or later you can use NSJSONSerialization. If you have your JSON data in a string you can do:
NSError *e = nil;
NSData *data = [stringData dataUsingEncoding:NSUTF8StringEncoding];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
Edit To get a specific value:
NSDictionary *firstObject = [jsonArray objectAtIndex:0];
NSString *projectName = [firstObject objectForKey:#"projName"];
I would recommend using JSONKit library for parsing.
Here's a tutorial on how to use it.
You will basically end up with a dictionary and use objectForKey with your key to retrive the values.
JSONKit
or
NSJSONSerialization(iOS 5.0 or later)
I have had success using SBJson for reading and writing json.
Take a look at the documentation here and get an idea of how to use it.
Essentially, for parsing, you just give the string to the SBJsonParser and it returns a dictionary with an objectForKey function. For example, your code might look something like:
NSDictionary* parsed = [[[SBJsonParser alloc] init] objectWithString: json];
NSString* projId = [parsed objectForKey:#"projId"];
Use SBJson
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSMutableDictionary *dicRes = [parser objectWithString:stringFromServer error:nil];
No need to use third party classes. Objective-c already includes handling JSON.
The class NSJSONSerialization expects an NSData object or reads from a URL. The following was tested with your JSON string:
NSString *json; // contains your example with escaped quotes
NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingAllowFragments error:&error]
For more options with NSJSONSerialization see the documentation.