[英]MagicalRecords import data from JSON / NSDictionary. Import relationships
[英]JSON to NSDictionary. Shouldn't be this hard?
當我將JSON數據放入NSDictionary時,我收到錯誤*。 我收到的錯誤是因為密鑰未被識別。
*錯誤[__ NSCFArray objectForKey:]:無法識別的選擇器發送到實例0x8d26cd0
JSON字符串輸出如下所示:
[{"Username":"TestUsername"}]
我正在使用的代碼:
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(@"%@",text);
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
//Fails when using NSDictionary instead of NSArray
NSLog(@"json: %@", [json objectForKey:@"Username"]);
//NSLog(@"json: %@", json[0]);
}
當我使用NSArray時,這是輸出:
{
Username = Elder;
}
你的JSON
是Array
而不是Dictionary
。 在json數組中,第一個對象是字典。
更正了您的代碼:
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(@"%@",text);
NSError *error;
NSArray *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
//Fails when using NSDictionary instead of NSArray
NSLog(@"json: %@", [json[0] objectForKey:@"Username"]);
//NSLog(@"json: %@", json[0]);
}
將代碼更改為
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
//Check the array count if required, if count is 0, jsonArray[0] crashes
NSString *userName = [jsonArray[0] objectForKey:@"Username"];
NSLog(@"json: %@", userName);
在您的代碼中, JSONObjectWithData:
返回NSArray
而不是NSDictionary
。 所以objectForKey:
在NSArray
造成崩潰。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.