2013-11-28 24 views
0

我使用網絡服務來拉出JSON格式的一些信息時,我在做什麼錯。我可以在我的應用程序中查看它們。但是,當我嘗試將它們存儲在字典中時,我總是收到錯誤,說「valueId」值不符合。這是我任何想法設法從Web服務JSON存入的NSDictionary

NSMutableArray *results = [NSMutableArray array]; 

    for (id courseDictionary in response) { 

    ListOfCourses *course = [[ListOfCourses alloc] initWithDictionary:courseDictionary]; 
    [results addObject:course]; 

    } 

,在我ListOfCourses.m我有

- (id)initWithDictionary:(NSDictionary *)dictionary 
{ 

    self = [super init]; 
    if (self) { 

    _courseId = [NSNumber numberWithInt:[[dictionary valueForKey:@"courseId"] 
    _room1 = [dictionary objectForKey:@"room1"]; 
    _subjectCode = [dictionary objectForKey:@"subjectCode"]; 

    } 
    return self; 

} 

JSON文件

{ 
    "Template":{ 
     "Room1":"Day 1 room name/number; string; required; 10 characters", 
    "SubjectId":"Subject identifier; number; required; Subject identifier must exist", 

    { 
    "Links":[ 
     { 
     "Rel":"self", 
     "Href":"/api/courses/2" 
     }, 
     { 
     "Rel":"collection", 
     "Href":"/api/courses/" 
     } 
    ], 
    "Item":{ 
     "Link":{ 
     "Rel":"self", 
     "Href":"/api/courses/2" 
     }, 
     "Id":1, 
     "SubjectCode":"D9920", 
     "Room1":"S2153" 

} 

更新:我返回對象的集合,當我做到這一點

_courses = (NSArray *)[response objectForKey:@"Collection"]; 

我是ab le查看對象。我試圖把它們各自獨立成字典現在

+2

顯示你的json〜! – meda

+2

你可以發佈錯誤日誌嗎? – Ilario

+0

你在做什麼(非常)不清楚,但至少可以包括你在右邊界切斷的代碼嗎? –

回答

0

更改您的代碼行從:

_courseId = [NSNumber numberWithInt:[[dictionary valueForKey:@"courseId"]

到:

_courseId = [NSNumber numberWithInt[[dictionary valueForKey:@"Id"] intValue]]; 

如果這不會幫助請張貼json文件。

// EDITED

您可以使用[字典valueForKey:@ 「courseId」]但關鍵是身份證,請更改courseId爲Id。

//擴展

你必須嵌入在詞典試試這個:

NSDictionary *dic = dictionary[@"Item"]; 
    _courseId = [NSNumber numberWithInt:[dic[@"Id"] intValue]]; 
    _room1 = dict[@"Room1"]; 
    _subjectCode = dict[@"SubjectCode"]; 

如果它不工作,你必須來發表您的JSON文件的開頭。

+0

試過,我仍然得到這個[<__ NSCFString 0x8368810> valueForUndefinedKey:]:此類不是密鑰編碼兼容的密鑰ID。 – user2433194

+0

你可以發佈你的json的開始嗎? – Greg

+0

我要去嘗試,開始了JSON已經公佈 – user2433194

0

當你打開和關閉流走的實體,您應該使用NSCoding協議。有很多方法可以用JSON來做到這一點,例如JSONCoding

這些類型的問題,將有資格作爲重構氣味:你不應該擔心的東西是如何捆綁起來。

相關問題