1

I have JSon Values in NSString. I am trying to parse the values from the NSString JSonValue.

NSString Values like:

result = [{"no":"01","send":"2010-05-03 01:26:48","from":"0000000000","to":"1111111111","text":"abcd"}] 

I have tried the below code to parse the values no, send, from, to, text.

 NSString *jsonString = result; NSDictionary *jsonArray = [jsonString jsonValue]; //Am trying to save the values from NSString to NSDictionary the app getting crash here. NSLog(@"JsonDic : %@", jsonArray); 

Can anyone please help to parse the JSon values from NSString? Thanks in advance.

1
  • So you have searched stackoverflow and couldn't find any questions about how to parse JSON on iOS? Very strange... Commented Jul 4, 2012 at 12:38

3 Answers 3

1

For iOS5, you can use NSJSONSerialization.

NSError *error; NSString *json = @"[{\"no\":\"01\",\"send\":\"2010-05-03 01:26:48\",\"from\":\"0000000000\",\"to\":\"1111111111\",\"text\":\"abcd\"}]"; id jsonObj = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&error]; 

And you can also use SBJson.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your response. I have solved the problem and i can get the values. Thanks for your help.
0

Gopinath. I have mentioned code please try this one. I have tested i can get the no.

SBJSON *parser = [[SBJSON alloc] init]; NSDictionary *jsonArray = (NSDictionary *) [parser objectWithString:result error:nil]; NSLog(@"jsonArray : %@", jsonArray); NSArray *depositArray = [jsonArray valueForKey:@"no"]; NSLog(@"depositArray : %@", depositArray); 

Please test and let me know if you face any problem. Thanks.

Comments

0

Parsing JSON is a bit more complicated.

For my part, i use SBJSON, you can download it from here : http://stig.github.com/json-framework/

It is a simple set of file to put in your project. I suggest to put in a dedicated group.

Once you've done that, here is the code you could use :

NSError *jsonError; NSDictionary *jsonResults; SBJsonParser* parser = [[SBJsonParser alloc]init]; jsonResults = [parser objectWithString:YOURSTRING error:&jsonError ]; if (jsonResults == nil) { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:[NSString stringWithFormat:@"Something bad happened with JSON : %@ : %@",YOURSTRING,[ jsonError localizedDescription ]] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alertView show]; [alertView release]; } else { NSLog(@"JSON result : %@",jsonResults); } 

If you need more infos, you can find good tutorial on SBJSon, for instance here : http://www.touch-code-magazine.com/tutorial-fetch-and-parse-json/

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.