【问题标题】:&amp special character issue in json string&amp json字符串中的特殊字符问题
【发布时间】:2016-08-06 21:42:03
【问题描述】:

我有一个字典数组像这样转换成 JSON 字符串,

 NSMutableArray *returnArray = [NSMutableArray new];

    NSMutableDictionary *temp1= [NSMutableDictionary new];
    [temp setObject:@"item1" forKey:@"notes"];
    NSMutableDictionary *temp2= [NSMutableDictionary new];
    [temp2 setObject:@"item & item2 " forKey:@"notes"];

    NSString *json = [self aryToJSONString:allSync];

json 转换器:

-(NSString *)aryToJSONString:(id) ary{

NSError *error; 
NSString *jsonString;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ary 
                                                   options:0 // Pass 0 if you don't care about the readability of the generated string
                                                     error:&error];

if (! jsonData) {
    NSLog(@"Got an error: %@", error);
} else {
    jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
   }
    return jsonString;
}  

转换后的 JSON:

[{"notes":"item"},{"notes":"item1 & item2"}]

然后将其发布到服务器 (PHP)。服务器接收到这样的无法解析的 json 字符串,

[{\"notes\":\" item1 \"},{\"notes\":\"item1 ","item2\"}]":"

&amp特殊字符问题如何处理?

编辑:

PHP 代码:

 $json = $_REQUEST['json'];
       $json = stripslashes($json);
       $jsonArr = json_decode($json, true);

       while($item = array_shift($jsonArr))
       {
           foreach($item as $key=>$value)
           {
           }
       }

【问题讨论】:

  • 尝试像这样使用字符串替换str_replace('&','&',$string)
  • 你能分享你的php代码吗?
  • PHP 代码共享请查看@Mubashar Abbas
  • 你为什么在做 stripslashes($json).. 你在做其他事情之前尝试过回显 $json 吗?
  • @Mubashar Abbas 我在 stripslashes($json) 之前回显了 json,它切断了后面的 '&' 符号,如 [{\"notes\":\" item1 \"},{\"notes\ ":\"item1

标签: php objective-c json url nsstring


【解决方案1】:

试试下面的代码:

在发布到服务器之前将 JSON 字符串传递给下面的方法。

-(NSString*)replaceSpecialCharsFromString:(NSString*)str
{
    str = [str stringByReplacingOccurrencesOfString:@"&" withString:@"&"];
    str = [str stringByReplacingOccurrencesOfString:@"<" withString:@"&lt;"];
    str = [str stringByReplacingOccurrencesOfString:@">" withString:@"&gt;"];
    return str;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-19
    • 1970-01-01
    相关资源
    最近更新 更多