1

我有一个 iPhone 应用程序,它从 web 服务返回一个字符串,其中包含“\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 来自 web 服务,如下所示

"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

4 回答 4

1

使用stringByReplacingOccurrencesOfString:withString:

jsonString = [[[jsonString stringByReplacingOccurrencesOfString:@"\n"
                                                        withString:@""] stringByReplacingOccurrencesOfString:@"\" withString:@""]
于 2012-10-10T10:40:52.230 回答
1

stringByReplacingOccurrencesOfString:withString:肯定会起作用,但是要删除反斜杠,请确保输入 2,因为仅输入 1 会避开引号。

jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\\" withString:@""];
于 2014-06-14T09:50:51.033 回答
0

我有一个想法\从你的 jsonString中删除反斜杠

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

它对我有用,它给了我一个有效的 JSON 字符串。

于 2015-04-07T13:28:11.143 回答
-1
jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];

jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\" withString:@""];
于 2012-10-10T14:07:01.253 回答