【问题标题】:can't read utf8 character from json in xcode无法从 xcode 中的 json 读取 utf8 字符
【发布时间】:2012-11-28 07:14:20
【问题描述】:

当我的 json 文件中有英文字符时,它会在数组中打印读取的 json,但是当我有藏文字符(utf8)时,它会打印 null。我正在粘贴我的 json 和 xcode 代码。请帮忙。这段代码是我正在尝试从core data tutorial

        int main(int argc, const char * argv[])
    {

        @autoreleasepool {
            // Create the managed object context
            NSManagedObjectContext *context = managedObjectContext();

            // Custom code here...
            // Save the managed object context
            NSError *error = nil;
            if (![context save:&error]) {
                NSLog(@"Error while saving %@", ([error localizedDescription] != nil) ? [error localizedDescription] : @"Unknown Error");
                exit(1);
            }
            NSError* err = nil;
            NSString* dataPath = [[NSBundle mainBundle] pathForResource:@"tsikzoe" ofType:@"json"];

            NSDictionary* tsikzoe = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath]options:kNilOptions error:&err];
 NSLog(@"Imported tsikzoe: %@",[tsikzoe objectForKey:@"wordDef"]);


        }
        return 0;
    }

这是 JSON

[{"id":1,"dictionaryType":1,"word":"༼༡༠༠༦༽ སྲོང་བཙན་ཆོས་ཀྱི་རྗེ་བོ་ཡབ་ཡུམ་གསུམ།","wordDef":"རྒྱལ་པོ་སྲུང་བཙན་སྒམ་པོ། བལ་བཟའ་ཁྲི་བཙུན། རྒྱ་བཟའ་ཀོང་ཇོ་བཅས་གསུམ་ལ་ཟེར།","dateSubmitted":"2012-08-19 00:00:00","author":2,"authorName":"དུང་དཀར་ཚིག་མཛོད།"},
  {"id":2,"dictionaryType":1,"word":"༼༡༠༤༠༽ བསོ།","wordDef":"བསོ་བསོ་ཞེས་པའི་སྒྲའི་ཁྱད་པར་གྱི་མིང༌།","dateSubmitted":"2012-08-19 00:00:00","author":2,"authorName":"དུང་དཀར་ཚིག་མཛོད།"}]

【问题讨论】:

    标签: objective-c xcode json utf-8


    【解决方案1】:
     NSDictionary* tsikzoe = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath]options:kNilOptions error:&err];
    

    在这种情况下,您的 JASON 是一个数组,因此您需要访问该数组中的两个元素之一,即字典。

    字典 JSON 将具有这种格式

    {
    "employees": [    //right here! 
    { "firstName":"John" , "lastName":"Doe" }, 
    { "firstName":"Anna" , "lastName":"Smith" }, 
    { "firstName":"Peter" , "lastName":"Jones" }
    ]
    }
    

    Array JSON 将具有这种格式

    {
    [    //notice the difference. 
    { "firstName":"John" , "lastName":"Doe" }, 
    { "firstName":"Anna" , "lastName":"Smith" }, 
    { "firstName":"Peter" , "lastName":"Jones" }
    ]
    }
    

    【讨论】:

    • 老兄,我也尝试过使用数组,但没有运气,在这两种情况下,当我将内容用作英文时,它都有效 NSArray* tsikzoe = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath]options:kNilOptions 错误:&err ]; NSLog(@"导入的 tsikzoe: %@",tsikzoe);它正在输出 2012-11-29 11:12:49.384 tsikzoeMig[48217:303] Imported tsikzoe: (null) 你不认为这与编码有关吗
    • 试试这个以确保它使用 UTF8 编码: NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
    猜你喜欢
    • 2018-08-05
    • 1970-01-01
    • 1970-01-01
    • 2017-04-01
    • 2012-04-09
    • 1970-01-01
    • 1970-01-01
    • 2019-10-07
    • 1970-01-01
    相关资源
    最近更新 更多