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

孤街醉人 提交于 2019-12-04 03:04:37

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.

rahulchona

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];

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];
Jatin Rathod

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];
Sport

add this

 -(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint;  




-(NSString *)dictToJson:(NSDictionary *)dict {

     NSData *jsonData = [NSJSONSerialization dataWithJSONObject: dict
                                                   options:(NSJSONWritingOptions)    (prettyPrint ? NSJSONWritingPrettyPrinted : 0)
                                                     error:&error];

     if (!jsonData) {
        NSLog(@"bv_jsonStringWithPrettyPrint: error: %@", error.localizedDescription);
        return @"{}";
     } else {
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
     } 

 }

refer this Generate JSON string from NSDictionary in iOS

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!