我正在嘗試閱讀JSON從POST請求中獲取的內容。問題是,我無法嵌套字典。我試圖保存json,然後使用我的mac上的文件,一切正常!我用這梅索德得到來自服務器的JSON:如何正確讀取iOS上的JSON
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (!connectionError) {
if (![[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] isEqualToString:@"{\"response\":{\"status\":\"fail\",\"message\":\"Please use a POST request.\",\"code\":4012}}"]) {
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:@"/Users/David/Downloads/Test"] options:kNilOptions error:&error]; //This returns a other JSON than the JSON stored on my mac
NSArray *array = [dict objectForKey:@"list"];
NSMutableDictionary *mutableDict = [NSMutableDictionary new];
for (NSInteger i = 0; array.count>i; i++) {
NSDictionary *listDictionary = [array objectAtIndex:i];
NSDictionary *defenition = [listDictionary objectForKey:@"definition"];
[mutableDict setObject:[defenition objectForKey:@"form"] forKey:[listDictionary objectForKey:@"term"]];
}
NSLog(@"%@", mutableDict);
}
}
}];
現在的問題,我必須使用其他梅索德獲得從NSURLConnection的正確的JSON?
感謝
編輯
這是我下載了JSON和我有我的Mac上的內容:
{
"response" : {
"status" : "success",
"code" : "200",
"message" : "OK"
},
"list" : [
{
"term" : "Black",
"context" : "",
"created" : "2014-04-17 20:34:33",
"updated" : "",
"definition" : {
"form" : "Schwarz",
"fuzzy" : 0,
"updated" : "2014-04-17 21:35:50"
},
"reference" : "",
"tags" : []
}
]
}
這是我從字典 「字典」 獲得:
{
"response" : {
"status" : "success",
"code" : "200",
"message" : "OK"
},
"list" : [
{
"term" : "Black",
"context" : "",
"created" : "2014-04-17 20:34:33",
"updated" : "",
"reference" : "",
"tags" : []
}
]
}
請注意,詞典「定義」已經丟失!
爲什麼你從文件中讀取JSON而不是使用通過網絡接收的數據(大概是在NSData對象中)? –
爲什麼你使用那個時髦的字符串比較來檢查失敗? –
您正在獲得不同的值**,因爲您正在閱讀文件**。 –