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?
Swift 4: Worth Considering
instead of
I can't say what is the error, because I tried here and worked.
I tried with
NSString *vCard = nil
andNSString *vCard = @"SOMESTRING"
, both cases it worked.Make sure
[BRContacts getContacts]
returning aNSString
, and I just rewrite to a modern syntax theNSDictionary
declaration.Ok I solved. It was a problem related to this line:
this response of GCDWebServer doesn't want a JSON
NSData
but aNSDictionary
: the error is just becauseresponseWithJSONObject
process the input for create a JSON object (and I passed a JSON "pre-processed" object). So my error is not related to my initial code so I updated it just now for future reference, I solved using:According to the documentation for similar problem be sure to follow this rules: