Search code examples
objective-cjsonnsjsonserialization

Issue in converting NSDictionary to json string, replacing / with \/


i want to convert NSDictionary to json string.everything is working fine, i have a small issue that is described as follows: I have a following code for conversion of NSDictionary to NSString:

-(NSString *)dictToJson:(NSDictionary *)dict
{
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
   return  [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
}

I am calling the method as:

NSLog(@"%@", [self dictToJson:@{@"hello" : @"21/11/2014 10:07:42 AM"}]);

following is the output of this NSLog:

{
  "hello" : "21\/11\/2014 10:07:42 AM"
}

I am expecting following output, how can i achieve it:

{
      "hello" : "21/11/2014 10:07:42 AM"
}

it can be done by using stringByReplacingOccurrencesOfString method, but i don't want this to use. is there any other way to achieve the same?


Solution

  • Converting JSON object to String will escape the forward slash. That is why the back slash is added in your result.

    If you convert the string back to JSON object and logged the object, you can see the result as expected. Thus you can verify, there is nothing wrong with the string.