簡體   English   中英

iOS中的JSON錯誤:JSON寫入中的頂級類型無效

[英]JSON Error in iOS: Invalid top-level type in JSON write

我無法解決這個錯誤:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization writeJSONObject:toStream:options:error:]: Invalid top-level type in JSON write'

這涉及到這一塊代碼(基本上我正在創建一些JSON並將其發送到服務器)。 我已經檢查過服務器以查看套接字是否已打開,它是什么!

NSDictionary *blobData = [NSDictionary dictionaryWithObjectsAndKeys:
                          sendString,@"string",
                          nil];
NSString *blobString = [[NSString alloc]
                        initWithData:[NSJSONSerialization dataWithJSONObject:blobData options:kNilOptions error:&error]
                        encoding:NSUTF8StringEncoding];
NSLog(@"Blob Created: %@", blobString);
NSDictionary *requestData = [NSDictionary dictionaryWithObjectsAndKeys:
                             @"send_string",@"request_type",
                             [NSNumber numberWithInt:0],@"security_level",
                             @"ios",@"device_type",
                             //No Email Provided, This is just for testing
                             blobData,@"blob",
                             nil];

NSData *JSONRequestData = NULL;
if ([NSJSONSerialization isValidJSONObject:requestData]) {
    NSLog(@"Proper JSON Object");
    JSONRequestData = [NSJSONSerialization dataWithJSONObject:requestData options:kNilOptions error:&error];
}
else {
    NSLog(@"requestData was not a proper JSON object");
    return FALSE;
}
NSLog(@"Error:%@",[[error userInfo] objectForKey:@"NSDebugDescription"]);
NSLog(@"Contents of JSONRequestData: %@",[[NSString alloc] initWithData:JSONRequestData encoding:NSUTF8StringEncoding]);
[NSJSONSerialization writeJSONObject:JSONRequestData toStream:outputStream options:0 error:&error];

我是否錯誤地創建了JSON對象? 也許我處理“blob”的方式有問題

這是我創建JSONRequestData后NSLogs打印的內容

{"security_level":"0","request_type":"send_string","device_type":"ios","blob":{"string":"hello"}}

writeJSONObject期望您要發送的實際反序列化對象,因此在這種情況下,您需要將requestData對象傳遞給它,而不是像JSONRequestData那樣:

NSJSONSerialization writeJSONObject:requestData toStream:outputStream options:0 error:&error];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM