简体   繁体   中英

remove “\n” and “\” from nsstring in iPhone…?

I have a iPhone application which return me a string from webservice with escape characters like "\\n" and "\\". Now I want to add this string in nsdictionary. for that I do below

    NSMutableArray *keyArray = [[NSMutableArray alloc] initWithCapacity:1];
NSMutableArray *valueArray = [[NSMutableArray alloc] initWithCapacity:1];

[valueArray addObject:strVerifiedReceipt];
[keyArray addObject:@"PAYMENT_RECEIPT"];

NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:valueArray forKeys:keyArray];
NSString* jsonString = [jsonDictionary JSONRepresentation];

here jsonString return me strVerifiedReceipt with escape characters come from webservice like below

 "PAYMENT_RECEIPT": "{\\n\\"receipt\\":{\\"original_purchase_date_pst\\":\\"2012-10-10 03:29:12 America/Los_Angeles\\", \\"unique_identifier\\":\\"977ce60f38d875d12d0f1d7fe583d1d5e61f99e8\\", \\"original_transaction_id\\":\\"1000000056917869\\", \\"bvrs\\":\\"2.0\\", \\"transaction_id\\":\\"1000000056917869\\", \\"quantity\\":\\"1\\", \\"product_id\\":\\"com.cornerstonehealthtechnologies.meanexus.Nexus010\\", \\"item_id\\":\\"544678366\\", \\"purchase_date_ms\\":\\"1349864952265\\", \\"purchase_date\\":\\"2012-10-10 10:29:12 Etc/GMT\\", \\"original_purchase_date\\":\\"2012-10-10 10:29:12 Etc/GMT\\", \\"purchase_date_pst\\":\\"2012-10-10 03:29:12 America/Los_Angeles\\", \\"bid\\":\\"com.cornerstonehealthtechnologies.meanexus\\", \\"original_purchase_date_ms\\":\\"1349864952265\\"}, \\"status\\":0}", 

Use stringByReplacingOccurrencesOfString:withString:

jsonString = [[[jsonString stringByReplacingOccurrencesOfString:@"\n"
                                                        withString:@""] stringByReplacingOccurrencesOfString:@"\" withString:@""]

stringByReplacingOccurrencesOfString:withString: will definitely work, but to remove the backslashes, make sure you put 2, because putting just one will just escape the quotation mark.

jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\\" withString:@""];

I have an idea to remove backslash \\ from your jsonString

jsonString = [NSString stringWithFormat:@"%s",[jsonString UTF8String]]

And it is working for me and it gives me a valid JSON string.

jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];

jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\" withString:@""];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM