When using Nsserialization to convert an object to a JSON string in iOS, there is a problem with backslashes
http://segmentfault.com/q/1010000000576646
NSDictionary *dic = @{@"url": @"http://..."}; NSLog(@"%@", dic); NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil]; NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; NSLog(@"%@", jsonString);
Execution Result:
2014-06-12 14:44:19.427 main[64877:1322484] { url = "http://..."; } 2014-06-12 14:44:19.429 main[64877:1322484] { "url" : "http:\/\/..." }
The URL address in the converted JSON string is escaped:(
Using string substitution can be remedied afterwards:
stringByReplacingOccurrencesOfString:@"\\" withString:@""];
--------------------------------------------------------------------------
IOS removes escape characters from JSON
Today to help friends to get this problem, the JSON return is all with ' \ ', so to remove the backslash, but OC inside the ' \ ' is an escape character, not directly with the "\" or the like, after a search, found the OC on the expression of the escape character, as follows:
\a-sound Alert
\b-Backspace
\f-form Feed
\ n-Line break
\ r-Enter
\ t-Horizontal tab
\v-Vertical tab
\ \-Back slash
\ "-Double quotation marks
\ '-Single quote
Then know how to say ' \ ', removing this is a matter of traversal. The code is as follows:
1 nsmutablestring *responsestring = [nsmutablestring stringwithstring:[request responsestring]];2 NSString * character = Nil;3 for (int i = 0; i < responsestring.length; i + +) {4 character = [Responsestring Substringwith Range:nsmakerange (i, 1)];5 if ([character isequaltostring:@ "\"]) 6 [responsestring deletecharactersinrange : Nsmakerange (i, 1)];7 }
Of course the other escape symbols are removed in the same vein.
**ios JSON request to escape the string and return the JSON to escape