为什么NSJSONSerialization的代码总是崩溃?

时间:2013-03-10 15:53:23

标签: objective-c nsjsonserialization

//
//  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;
}

我得到的错误是:

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 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

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

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

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