Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 552
Faisal Ikwal Avatar asked Nov 21 '14 04:11

Faisal Ikwal


3 Answers

Convert to response to Data with option PrettyPrinted and then convert Data to string using utf8 encoding Code :

    NSDictionary *dictResponse = responseObject[0];

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictResponse options:NSJSONWritingPrettyPrinted error:nil];


    NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
like image 104
Jatin Rathod Avatar answered Oct 18 '22 07:10

Jatin Rathod


Nsdictionary - to - string

NSError * err;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:response options:0 error:&err];
NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

string - to - NSDictionary

NSError * err;
NSDictionary * response = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:[NSData dataFromString:str] options:NSJSONReadingMutableContainers error:&err];
like image 22
rahulchona Avatar answered Oct 18 '22 08:10

rahulchona


Try this,

NSData *json = [NSJSONSerialization dataWithJSONObject:dict
                                               options:0
                                                 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
// This will be the json string in the preferred format 
jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\\/" withString:@"/"];

// And this will be the json data object 
NSData *processedData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
like image 2
Alex Andrews Avatar answered Oct 18 '22 07:10

Alex Andrews