dsgm5631 2016-04-15 04:29
浏览 289

&amp json字符串中的特殊字符问题

I have an array of dictionary converted into JSON string like this,

 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 converter:

-(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;
}  

Converted JSON:

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

and then POST it to the server (PHP). The server receives unparsable json string like this,

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

How can I handle &amp special character issue?

EDIT:

PHP Code:

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

       while($item = array_shift($jsonArr))
       {
           foreach($item as $key=>$value)
           {
           }
       }
  • 写回答

1条回答 默认 最新

  • douguai4653 2016-04-15 04:52
    关注

    Try below code:

    Pass JSON string to below method before posting to server.

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

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退