Convert NSDictionary containing NSArray to JSON
json, nsarray, nsdictionary, nsjsonserialization, objective-c
Solution
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"
]
}
Problem
I have a `NSDictionary` containing a few different objects, among which is a `NSArray`. Elements in the array are `NSDictionary`-representations of a custom object. I have renamed the properties and removed some others for simplicity. First I try to simply serialize the `NSArray` like this, just to see what it would look like: ``` NSData *jsonData = [NSJSONSerialization dataWithJSONObject:myArray options:NSJSONWritingPrettyPrinted error:&writeError]; NSLog(@"%@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]); ``` The result looks like this, which is what I expected: ``` [ { "someProperty" : "Value 1" }, { "someProperty" : "Value 2" } ] ``` However, when I add the (unencoded) array to a `NSDictionary` and serialize that in stead the array looks different: ``` NSMutableArray *myArray = [NSMutableArray array]; [myArray addObject:[object1 dictionaryRepresentation]]; // dictionaryRepresentation returns a NSDictionary [myArray addObject:[object2 dictionaryRepresentation]]; NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; [dictionary setObject:myArray forKey:@"myArray"]; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&writeError]; NSLog(@"%@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]); ``` Now the result looks like this: ``` { myArray = ( { "someProperty" : "Value 1" }, { "someProperty" : "Value 2" } ); } ``` In stead of getting `"myArray" : [...]` I get `myArray = (...);` which is not the proper JSON representation. What is the correct way of making it use the JSON representation of the `NSArray` when adding it to the dictionary?