【问题标题】:remove "\n" and "\" from nsstring in iPhone...?从 iPhone 的 nsstring 中删除“\n”和“\”...?
【发布时间】:2012-10-10 10:35:53
【问题描述】:

我有一个 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}",

【问题讨论】:

标签: iphone json nsdictionary html-escape-characters


【解决方案1】:

使用 stringByReplacingOccurrencesOfString:withString:

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

【讨论】:

  • 谢谢,但已经尝试过这种类型的选项,但它只替换我的字符串中的 \n 而不是 \
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    我想从你的 jsonString 中删除反斜杠 \

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

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

    【讨论】:

      【解决方案4】:
      jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
      
      jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\" withString:@""];
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-21
      • 2013-02-28
      • 1970-01-01
      • 2014-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多