2016-03-08 75 views
0

Im通過JSON從網站加載數據庫。當我下載數據庫時,我使用UTF8使所有字符正確顯示,當我使用NSLOG時,它們全部顯示爲它應該顯示的內容。但是,當我使用JSON分析數據並嘗試過濾出幾個單詞時,帶有特殊字符的單詞變成這樣:「H \ U00f6ghastighetst \ U00e5g」它應該在哪裏說:「Höghastighetståg」。Xcode - JSON中的特殊字符

我試圖找到一種方法來使代碼在過濾後將文本轉換回UTF8,但不知何故我無法做到這一點。對於一些答案會非常有幫助。

NSError *error; 
NSString *url1 = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.pumba.se/example.json"] encoding:NSUTF8StringEncoding error:&error]; 

NSLog(@"Before converting to NSData: %@", url1); 

NSData *allCoursesData = [url1 dataUsingEncoding:NSUTF8StringEncoding]; 


NSMutableDictionary *JSONdictionary = [NSJSONSerialization 
             JSONObjectWithData:allCoursesData 
             options:kNilOptions 
             error:&error]; 
if(error) 
{ 
    NSLog(@"%@", [error localizedDescription]); 
} 
else { 
    NSMutableArray *allNames = [NSMutableArray array]; 
    NSArray* entries = [JSONdictionary valueForKeyPath:@"hits.hits"]; 

    for (NSDictionary *hit in entries) { 
     NSArray *versions = hit[@"versions"]; 
     for (NSDictionary *version in versions) { 
      NSDictionary *properties = version[@"properties"]; 
      NSString *status = [properties[@"Status"] firstObject]; 
      NSString *name = [properties[@"Name"] firstObject]; 
      if ([status isEqualToString:@"usable"]) { 
       [allNames addObject:name]; 
      } 
     } 
    } 

    NSLog(@"All names: %@", allNames); 
}} 

回答

0

嘗試

+ (NSString *)utf8StringEncoding:(NSString *)message 
{ 
    NSString *uniText = [NSString stringWithUTF8String:[message UTF8String]]; 
    NSData *msgData = [uniText dataUsingEncoding:NSNonLossyASCIIStringEncoding]; 
    message = [[NSString alloc] initWithData:msgData encoding:NSUTF8StringEncoding]; 
    return message; 
} 

+ (NSString *)asciiStringEncoding:(NSString *)message 
{ 
    const char *jsonString = [message UTF8String]; 
    NSData *jsonData = [NSData dataWithBytes:jsonString length:strlen(jsonString)]; 
    message = [[NSString alloc] initWithData:jsonData encoding:NSNonLossyASCIIStringEncoding]; 
    return message; 
} 

這個代碼可以幫助你

+ (NSDictionary *)jsonStringToObject:(NSString *)jsonString 
{ 
    NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; 
    NSDictionary *jsonResponse; 
    if (data) 
     jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]; 

    return jsonResponse; 
} 

+ (NSString *)objectToJsonString:(NSDictionary *)dict 
{ 
    NSError *error; 
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; 
    if (jsonData.length > 0 && !error) 
    { 
     NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 
     return jsonString; 
    } 
    return nil; 
} 
+0

謝謝Jose920405,但我不認爲我有能力知道如何在我目前的代碼中執行該操作,恐怕:/ – Dlindau

+0

而不是「H \ U00f6ghastighetst \ U00e5g」我現在收到「H \\ 366ghastighetst \\ 345g」。 – Dlindau