Invalid top-level type in JSON write

Massimo Polimeni picture Massimo Polimeni · Dec 10, 2015 · Viewed 12.3k times · Source

I'm trying to create a simple JSON object but I still get error and I know what's wrong in my code:

NSString *vCard = [BRContacts getContacts]; // this is just a string, could be nil
NSDictionary *JSONdic = nil;
if (vCard)
{
    JSONdic = [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"status",vCard,@"data", nil];
}
else
{
    JSONdic = [NSDictionary dictionaryWithObjectsAndKeys:@"0",@"status",@"vCard is empty",@"error", nil];
}
NSError *error = nil;
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:JSONdic options:NSJSONWritingPrettyPrinted error:&error];
return [GCDWebServerDataResponse responseWithJSONObject:JSONdata];

The exception is

Invalid top-level type in JSON write

I checked also JSONdic and it's not nil in every case. Any suggestions?

Answer

Felipe Docil picture Felipe Docil · Dec 10, 2015

I can't say what is the error, because I tried here and worked.

I tried with NSString *vCard = nil and NSString *vCard = @"SOMESTRING", both cases it worked.

NSString *vCard = @"SOMESTRING"; // this is just a string, could be nil
    NSDictionary *JSONdic = nil;
    if (vCard) {
        JSONdic = @{@"status" : @"1", @"data" : vCard};
    } else {
        JSONdic = @{@"status" : @"0", @"error" : @"vCard is empty"};
    }
    NSError *error = nil;
    NSData *JSONData = [NSData data];

if ([NSJSONSerialization isValidJSONObject:JSONdic]) {
    JSONData = [NSJSONSerialization dataWithJSONObject:JSONdic options:NSJSONWritingPrettyPrinted error:&error];
}

Make sure [BRContacts getContacts] returning a NSString, and I just rewrite to a modern syntax the NSDictionary declaration.