当我在我的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":"དུང་དཀར་ཚིག་མཛོད།"}]
答案 0 :(得分:0)
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" }
]
}