Created
October 18, 2021 12:42
-
-
Save calderaro/36496d56ad1857a08ae185eae94d7353 to your computer and use it in GitHub Desktop.
Parsing JSON in Objective C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// json s string for NSDictionary object | |
NSString *s = @"{\"temperature\": -260.65, \"humidity\": 54.05, \"time\": \"2016-03-14T09:46:48Z\", \"egg\": 1, \"id\": 6950, \"no2\": 0.0}"; | |
// comment above and uncomment below line, json s string for NSArray object | |
// NSString *s = @"[{\"ID\":{\"Content\":268,\"type\":\"text\"},\"ContractTemplateID\":{\"Content\":65,\"type\":\"text\"}}]"; | |
NSData *jsonData = [s dataUsingEncoding:NSUTF8StringEncoding]; | |
NSError *error; | |
// Note that JSONObjectWithData will return either an NSDictionary or an NSArray, depending whether your JSON string represents an a dictionary or an array. | |
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error]; | |
if (error) { | |
NSLog(@"Error parsing JSON: %@", error); | |
} | |
else | |
{ | |
if ([jsonObject isKindOfClass:[NSArray class]]) | |
{ | |
NSLog(@"it is an array!"); | |
NSArray *jsonArray = (NSArray *)jsonObject; | |
NSLog(@"jsonArray - %@",jsonArray); | |
} | |
else { | |
NSLog(@"it is a dictionary"); | |
NSDictionary *jsonDictionary = (NSDictionary *)jsonObject; | |
NSLog(@"jsonDictionary - %@",jsonDictionary); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment