Search code examples
objective-cjson-api

How do i serialize an empty jsonapi object


i have a jsonapi object that i need to serialise into a string.

{\n  \"data\" : [\n\n  ]\n}

but this causes the error

Terminating app due to uncaught exception 'NSInvalidArgumentException', 
reason: '*** +[NSJSONSerialization dataWithJSONObject:options:error:]:    
Invalid top-level type in JSON write'

this is the code that i am using to convert the json object into a string:

    NSError * error;
NSData * jData = [NSJSONSerialization dataWithJSONObject:[notification.userInfo objectForKey:@"data"] 
options:NSJSONWritingPrettyPrinted error:&error];

NSString *jString = [[NSString alloc] initWithData:jData encoding:NSUTF8StringEncoding];

Hope someone can help me with this problem.(that does not involve manually removing the \ and \n)


Solution

  • To convert a json object into string you should first get it into a NSData then use the encoding of NSUTF8StringEncoding to turn it into a NSString.

    NSDictionary *jsonDict = {\n  \"data\" : [\n\n  ]\n}
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]