Get values from JSON string - Objective C - objective-c

I have this JSON response string:
{"d":"{\"ID_usuario\":\"000130\",\"Nombre\":null,\"Vipxlo\":0,\"Provmun\":null,\"Descuentos\":null,\"Listaviplocal\":null}"}`
With this code:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//Check valid signal
connection = nil;
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
//data =nil;
NSArray *jsonArray = [responseString JSONValue];
How can I do it?

When you can afford to require iOS 5 you should try NSJSONSerialization.
Your code could look like this but I suggest reading the Docs first.
NSArray* jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:someError]

This JSON should result in a Dictionary
NSDictionary *jsonDict = [responseString JSONValue];
then use:
[jsonDict objectForKey:#"d"];

Try using the SBJasonParser library for iOS.
You can then use this code (for all iOS versions):
SBJsonParser* parser = [[[SBJsonParser alloc] init] autorelease];
NSDictionary* myDict = [parser objectWithString: responseString];
Note: Your code above has a JSON Dictionary but you were trying to access it as an Array.

Related

How to create true/false in JSON in Objective-C

How do I get true/false (instead of "true"/"false") in json from a NSDictionary using NSJSONSerialization dataWithJSONObject? What keys should I store in the dictionary to get that?
NSNumber objects containing a BOOL are mapped to JSON "true" and "false".
So just use #YES, #NO, or generally #(someBOOL). For example:
NSDictionary *dict = #{#"this is": #YES};
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// {"this is":true}

App crashing because NSArray objectforkey: Objective C

I am trying to parse some Json with Objective C.
My problem is that I am getting the correct json back but when I try parse some of the json my app crashes.
// i will use a code from connect to DB tutorial
NSString *strURL = [NSString stringWithFormat:#"http://www.ddproam.co.za/Central/Asset/AssetsWithSerial?Serial=S00000001"];
// to execute php code
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
// to receive the returend value
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSLog(#"Login response:%#",strResult);
NSError *error;
//parse out the json data
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:dataURL //1
options:kNilOptions
error:&error];
NSArray* defineJsonData = [json objectForKey:#"AssetDesc"]; //2
NSLog(#"value: %#", defineJsonData); //3
Here is my json:
[{"AssetID":1,"AssetName":"Asset 1","AssetDesc":"This is a manually inserted Asset","AssetTypeID":1,"AssetTypeDesc":"This is a manually inserted Asset Type"}]
I am trying to get the AssestName out of the string. I must be doing something wrong.
The whole thing is an array containing a dictionary, not a dictionary containing an array...
This is a very dirty way to get the value you want - you want to write something more safe than this. Try checking the type of class returned before you try to use it...
NSArray* json = [NSJSONSerialization JSONObjectWithData:dataURL //1
options:kNilOptions
error:&error];
NSDictionary* defineJsonData = [json lastObject]; //2
NSLog(#"value: %#", [defineJsonData objectForKey:#"AssetDesc"]); //3

Decode JSON to NSArray or NSDictionary

I hope to decode the JSON data below:
{
"content":
[
{
"1":"a",
"2":"b",
"3":"c",
"4":"d",
"mark":"yes"
}
]
}
Not sure if put it in NSArray or NSDictionary
Welcome any comment
which iOS version are you using? in iOS 5 you have the NSJSONSerialization class to parse JSON data, if you need to target older iOSs or MAC OSX you should use third parties lib such as SBJSON. The string posted will be a NSDictionary with an array with one dictionary. The array will be accessible using the key #"content"
In code:
NSString * jsonString = #"blblblblblb";
NSStringEncoding encoding;
NSData * jsonData = [jsonString dataUsingEncoding:encoding];
NSError * error=nil;
NSDictionary * parsedData = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
In SWIFT 2.0:
let jsonString = "blblblblblb"
let encoding = NSUTF8StringEncoding
let jsonData = jsonString.dataUsingEncoding(encoding)
guard let jData = jsonData else {return}
do {
let parsedData = try NSJSONSerialization.JSONObjectWithData(jData, options: [])
} catch let error {
print("json error: \(error)")
}
[UPDATE]
The NSJSONSerialization class is also available for 10.7 my comment wasn't correct.
That particular string will decode into an NSDictionary because the outermost thing is a JSON object which maps onto a NSDictionary for every JSON implementation I have ever seen. If you want to process an arbitrary string, you'll need to test what you get back
NSError *jsonError;
id parsedThing = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
if (parsedThing == nil)
{
// error
}
else if ([parsedThing isKindOfClass: [NSArray class]])
{
// handle array, parsedThing can be cast as an NSArray safely
}
else
{
// handle dictionary, parsedThing can be cast as an NSDictionary
// NB only dictionaries and arrays allowed as long as NSJSONReadingAllowFragments
// not specified in the options
}
stringWithContentsOfFile:encoding: is deprecated in iOS<6
for iOS 6+
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"contents" ofType:#"json"];
NSError * error=nil;
NSString *jsonString = [NSString stringWithContentsOfFile:filePath encoding:nil error:&error];
NSData * jsonData = [jsonString dataUsingEncoding:nil];
NSArray * parsedData = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
contents.json file is in your bundle.
You can do the following:
NSData *data = ...; //JSON data
NSError *jsonError = nil;
[NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
You will get back an NSDictionary containing an NSArray containing a single NSDictionary containing five NSString objects.
I used google speech recognition API and I was getting a json response which was not directly parsable on iOS. Results samples were like :
First I tried saying Hello 1 2 3 which was recognised without issues. Json response was :
{"result":[]}
{"result":[{"alternative":[{"transcript":"hello 123","confidence":0.59780568},{"transcript":"hello 1 2 3"}],"final":true}],"result_index":0}
Or when talked for too long, I got a 404 HTML like below :
<html><title>Error 400 (Bad Request)!!1</title></html>
And when I spoke gibberish , I got :
{"result":[]}
So to parse all such response, I used the below code :
NSString *msg = #"Could not synthesize !";
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"responseString: %#",responseString);
if([responseString containsString:#"transcript"]&&responseString.length>25)
{
responseString = [responseString stringByReplacingOccurrencesOfString:#"{\"result\":[]}" withString:#""];
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[responseString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
if(dictionary!=nil)
if(dictionary.allValues.count>0)
{
NSArray *array =[dictionary valueForKeyPath:#"result.alternative.transcript"];
if(array)
{
NSArray *array2 = [array objectAtIndex:0];
if(array2)
{
NSLog(#"%#",[array2 objectAtIndex:0] );
msg = [array2 objectAtIndex:0];
};
}
}
}
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Google Response" message:msg delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
Hope this helps someone.

parse JSON in objectiveC (SBJSON) objects and arrays

So far I've discovered in JSON that everything enclosed in { } are objects (objC : NSDictionary) and anything enclosed in [ ] is an array (objC : NSArray).
I've read and re-read this article about the subject>
How to parse JSON into Objective C - SBJSON
I have a .json file with the data modeled like this:
http://elbee101.com/dummySchedule.json
...and now for the code:
SBJSON *parser = [[SBJSON alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://elbee101.com/dummySchedule.json"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *schedule = [parser objectWithString:json_string error:nil];
NSDictionary *day = [schedule objectForKey:#"day"];
NSArray *myList = [day objectForKey:#"name"];
NSLog(#"myList %#", myList);
NSArray *numLaps = [myList objectAtIndex:0];
NSLog(#"numlaps%# ", numLaps);
I'm getting "myList (null)" and "numlaps (null)" from the above code?!#
The question: Can somebody please set me straight on the ordering of objects and arrays with respect to my json data? I want to drill down the tree so that I can access the 'day name', 'session starttime/endtime/sessionname', 'numlaps' & 'class' but I can't seem to get past the 'day' object/array(?)
What you're referring to as schedule is the object enclosed in the outermost {}. Try this:
NSDictionary *json = [parser objectWithString:json_string error:nil];
NSDictionary *schedule = [json objectForKey:#"schedule"];
Then continue as before.
Also, if you're on iOS 5 you can use the NSJSONSerialization class -- using it is pretty much the same, you might get better performance, and you don't have to worry about the hassles of using a third-party library.
call this where ever u need to parse
NSMutableArray *arr=[[NSMutableArray alloc] init];
arr=[[Headparse getArrayFromUrl:#"http://elbee101.com/dummySchedule.json"] retain];
NSLog(#"%#",[arr description]);
[arr release];
write this method as custom class use when ever you need
+(NSMutableArray *) getArrayFromUrl: (NSString *)actionType
{
NSMutableData *responseData1= [NSMutableData data] ;
responseData1 = [NSMutableData dataWithContentsOfURL:[NSURL URLWithString:actionType]];
// NSLog(#"%#",responseData1);
NSString *responseString1 = [[NSString alloc] initWithData:responseData1 encoding:NSUTF8StringEncoding];
//NSLog(#"REs:-->%#",responseString1);
//[responseData1 release];
responseData1 = nil;
NSMutableArray *responseArray = [[NSMutableArray alloc]init];
responseArray = (NSMutableArray *)[responseString1 JSONValue];
// NSLog(#"ghfchfvghv%#",responseArray);
[responseString1 release];
return responseArray;
}
This is how i use NSJsonSerialization for parsing the json object.
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://elbee101.com/dummySchedule.json"]];
NSError *err;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&err]; //
NSDictionary *schedule_dict = [json objectForKey:#"schedule"];
NSArray *days = [schedule_dict objectForKey:#"day"];//Days Array from day Object
NSDictionary *dayOne = [days objectAtIndex:0];
NSDictionary *dayTwo = [days objectAtIndex:1];
NSLog(#"THE DAY ONE : %#",dayOne);
NSLog(#"THE DAY TWO : %#",dayTwo);
Hope this may help you ....Note : If you don't want to go with NSJsonSerailization(consider reading of this) ,but still the parsing of json data like above will applicable in your case too.

Want to split the JSON from the URL not the response

I want to split the json part from this URL in my iPhone application.
http://vkontakte.ru/login_success.html#session={"expire":"1272008089","mid":"100172","secret":"9c8d8f0305","sid":"1131703552161ae352a1256402e3140d7cbde41b1602a93d15472c82"}
I tried and and saved the JSON into a NSString but what i am getting is
http://vkontakte.ru/api/login_success.html?session=%7B%22mid%22:113158415,%22secret%22:%227ce58bfcd3%22,%22sid%22:%2203831b43c1bb992f9477efbfe96e83f6ecff1c1b661315ac0a20719cf57a44%22,%22expire%22:0%7D
This is not coming in JSOn Format. Below is my code
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
NSURL *url = [request URL];
NSError* error;
NSLog (#"json path %#",url);
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSURLRequest *request1 = [NSURLRequest requestWithURL:url];
NSString *json_string = [url absoluteString];
NSArray *arr = [json_string componentsSeparatedByString:#"="];
json_string = [arr objectAtIndex:1];
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [json_string JSONValue];
NSLog(#"%#",error);
// Each element in statuses is a single status
// represented as a NSDictionary
for (NSDictionary *status in statuses)
{
// You can retrieve individual values using objectForKey on the status NSDictionary
// This will print the tweet and username to the console
NSLog(#"%# - %#", [status objectForKey:#"secret "], [[status objectForKey:#"mid"] objectForKey:#"sid"]);
}
return YES;
}
How can move further?
Try replacing:
NSString *json_string = [url absoluteString];
with
NSString *json_string = [[url absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];.
That's a really strange thing you're doing, though. Why does the URL have JSON in it?