删除" \ n"和" \"来自iPhone中的nsstring ......?

时间:2012-10-10 10:35:54

标签: iphone json nsdictionary html-escape-characters

我有一个iPhone应用程序,它从webservice返回一个带有转义字符的字符串,如“\ n”和“\”。现在我想在nsdictionary中添加这个字符串。为此我在下面做

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

这里jsonString返回strVerifiedReceipt,转义字符来自webservice,如下所示

"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}",

4 个答案:

答案 0 :(得分:1)

使用 stringByReplacingOccurrencesOfString:withString:

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

答案 1 :(得分:1)

stringByReplacingOccurrencesOfString:withString:肯定会有用,但要删除反斜杠,请确保放2,因为只放一个就会转义引号。

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

答案 2 :(得分:0)

我想从你的jsonString

中删除反斜杠\
jsonString = [NSString stringWithFormat:@"%s",[jsonString UTF8String]]

它适用于我,它为我提供了一个有效的JSON字符串。

答案 3 :(得分:-1)

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

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