In the first case, you are printing out the result of the JSON encoding operation.
In the second case, you are printing out the dictionary directly via NSLog
and not its JSON representation.
Update:
To see this, use this logging function instead of NSLog
:
void logThisObject(id obj)
{
if(obj == nil) {
NSLog(@"logObject: nil");
} else {
NSString *className = NSStringFromClass([obj class]);
NSLog(@"logObject: an %@: %@", className, obj);
}
}
Update 2:
void test_it()
{
NSArray *myArray = @[@"bla", @"foo"];
NSError *writeError = nil;
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[dictionary setObject:myArray forKey:@"myArray"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&writeError];
if(writeError) {
NSLog(@"an error happened: %@", writeError);
}
logThisObject([[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
}
this outputs proper JSON string:
logObject: an __NSCFString: {
"myArray" : [
"bla",
"foo"
]
}