-2

I am new in iPhone programming. Can anyone tell how parse the JSON string in iPhone? I'm using JSON parsing in my application. This is my JSON data: The JSON format is dz.

{  
"firstName": "John",  
"lastName": "Smith",  
"age": 25,  
 "address": {  
              "streetAddress": "21 2nd Street",  
          "city": "New York",  
          "state": "NY",  
         "postalCode": "10021"  
         }
}  

How can I do this parsing?

MMMM
  • 1,319
  • 1
  • 14
  • 32
areddy
  • 77
  • 2
  • 14

2 Answers2

1

You can use some JSON-Framework, i.e. https://github.com/stig/json-framework

iMx
  • 846
  • 1
  • 9
  • 23
0

Another solution would be NSRegularExpression Save the json Data in a string and then use the regex For example an Regex for the first line

NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\"firstName\":[^\"]*\"([^\"]*)\"" options:0 error:&error];
NSArray *matches = [regex matchesInString:theString options:0 range:NSMakeRange(0, [theString length])];
NSTextCheckingResult *match = [matches objectAtIndex:0];
NSLog([theString substringWithRange:[match rangeAtIndex:1]]);

Explanation: the regex looks for matches where you have "firstName": and then a variable number of signs except of "(because " inidicates where the data begins). ([^\"]) marks a specific range in the regex (so that you can extract it individually whit this line [theString substringWithRange:[match rangeAtIndex:1]]. [^\"] means every sign except "(because this is the end of data). I know this can be confusing at first. But If you take some time with it you will see that it's pretty easy.

arnoapp
  • 2,416
  • 4
  • 38
  • 70