簡體   English   中英

&json字符串中的特殊字符問題

[英]&amp special character issue in json string

我有一個字典數組像這樣轉換成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)
           {
           }
       }

試試下面的代碼:

在發布到服務器之前,將JSON字符串傳遞給以下方法。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM