Search code examples
objective-cxcodejsonnsloguidevice

Xcode how to NSLog a JSON


Is there any way to get NSLog to print out an entire JSON file. I am currently saying

NSString *deviceInfo = [NSString stringWithFormat:@"%@ %@",
                        [[UIDevice currentDevice]model], [[UIDevice currentDevice]systemVersion]];
NSDictionary *json = [deviceInfo JSONValue];
NSLog(@"json file = %@", json);

And it is printing out "json file = (null)"

Thanks Clinton


Solution

  • I think you’re misunderstanding what JSON is for. The string you’re passing to -JSONValue isn’t a valid JSON string, so it’s returning nil. You might as well just construct the dictionary yourself:

    UIDevice *device = [UIDevice currentDevice];
    NSDictionary *deviceInfo = [NSDictionary dictionaryWithObjectsAndKeys:[device model], @"deviceModel", [device systemVersion], @"deviceSystemVersion", nil];
    

    Then if you want the JSON string representation of the object (for sending to your server, for instance):

    NSString *jsonDeviceInfo = [deviceInfo JSONRepresentation];