2013-11-28 64 views
0

所以我有一個創建這樣和dictionary-錯誤使用NSJsonSerialization:在JSON無效的頂級類型寫

- (NSDictionary *) createPostData{ 
    NSMutableDictionary * requestDictionary = [[NSMutableDictionary alloc]init]; 
    [requestDictionary setValue:@"type://someStuff" forKey: @"$type"]; 
    [requestDictionary setValue:@"account" forKey:@"Widget"]; 
    NSMutableDictionary* messageDictionary = [[NSMutableDictionary alloc] init]; 
    [messageDictionary setValue:@"type://someStuff" forKey:@"$type"]; 
    [messageDictionary setValue: self.password forKey:@"Password"]; 
    [messageDictionary setValue:false forKey:@"RememberMe"]; 
    [requestDictionary setValue:messageDictionary forKey:@"Message"]; 
    return requestDictionary; 
} 

回報字典那麼我做這個

NSData *postData = [NSJSONSerialization dataWithJSONObject:postDataObject 
                  options:0 // Pass 0 if you don't care about the readability of the generated string 
                  error: &error]; 

功能我得到這個錯誤 -

Error - *** +[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write 

我真的不明白爲什麼,因爲我認爲我訂閱的規則在文檔 - 每個關鍵字都是一個字符串,我只使用NSDictionary和NSString的實例。

發生了什麼事?

+1

確定'postDataObject'正確分配您發佈的方法的返回值?你可以在控制檯檢查它並在這裏發佈結果嗎? –

+0

NSLog你的字典進入dataWithJSONObject。並注意setValue:false會導致內部字典過早終止。它應該是'setValue:@(false)' –

+0

'[messageDictionary setValue:false forKey:@「RememberMe」];''將從'messageDictionary'中移除鍵「@」RememberMe的對象。如果你真的想設置一個值,使用'@ NO'。 – Sebastian

回答

2

設置你的代碼塊

 if ([NSJSONSerialization isValidJSONObject:postDataObject]) { NSData *postData = [NSJSONSerialization dataWithJSONObject:postDataObject 
                 options:0 // Pass 0 if you don't care about the readability of the generated string 
                 error: &error];} 

,而不是

 NSData *postData = [NSJSONSerialization dataWithJSONObject:postDataObject 
                 options:0 // Pass 0 if you don't care about the readability of the generated string 
                 error: &error]; 
相關問題