2013-03-10 79 views
1
// 
// main.m 
// ASADeepDictionary 
// 
// Created by AndrewShmig on 3/10/13. 
// Copyright (c) 2013 AndrewShmig. All rights reserved. 
// 

#import <Foundation/Foundation.h> 
#import "ASADeepDictionary.h" 

int main(int argc, const char * argv[]) 
{ 
@autoreleasepool { 

NSDictionary *dic = @{@"key":@"value"}; 
NSMutableData *data = [[NSMutableData alloc] init]; 
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data]; 

[archiver encodeObject:dic]; 
[archiver finishEncoding]; 

id json = [NSJSONSerialization 
      dataWithJSONObject:data 
      options:0 
      error:nil]; 

NSLog(@"%@", json); 

} 

return 0; 
} 

错误是:为什么此代码与NSJSONSerialization总是崩溃?我越来越

2013-03-10 19:48:13.420 ASADeepDictionary[9451:303] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write' 
*** First throw call stack: 
(
    0 CoreFoundation      0x00007fff89fb70a6 __exceptionPreprocess + 198 
    1 libobjc.A.dylib      0x00007fff88fac3f0 objc_exception_throw + 43 
    2 CoreFoundation      0x00007fff89fb6e7c +[NSException raise:format:] + 204 
    3 Foundation       0x00007fff848bb49d +[NSJSONSerialization dataWithJSONObject:options:error:] + 249 
    4 ASADeepDictionary     0x0000000100001051 main + 321 
    5 libdyld.dylib      0x00007fff84bfd7e1 start + 0 
    6 ???         0x0000000000000001 0x0 + 1 

回答

2

第一个参数必须是NSDictionaryNSArray,不是NSData。你似乎误解了这种方法。它序列化传入的对象,它不是解析它。

+0

假设我发送一个NSString,那么它应该返回一个错误,但它的崩溃? – user1010819 2013-10-14 10:38:06

+0

@ user1010819为什么它应该返回一个错误?你违反了约束条件(你传递了一个字符串而不是字典)。 – 2013-10-14 10:47:00

+0

现在我正在检查它是否是有效的JSOn对象,然后将它传递给method.But它将返回error.I假定如果不传递正确的JSON对象它将返回给我一个错误。 – user1010819 2013-10-14 11:10:10

0
NSDictionary *dic = @{@"key":@"value"}; 

id json = [NSJSONSerialization 
      dataWithJSONObject:dic 
      options:0 
      error:nil]; 

NSLog(@"%@", [NSString stringWithUTF8String:[json bytes]]);