问题
//
// 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;
}
Error I am getting is:
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
回答1:
The first argument must be an NSDictionary
or an NSArray
, not an NSData
. You seem to be misunderstanding what this method does. It serializes the passed-in object, it doesn't parse it.
回答2:
NSDictionary *dic = @{@"key":@"value"};
id json = [NSJSONSerialization
dataWithJSONObject:dic
options:0
error:nil];
NSLog(@"%@", [NSString stringWithUTF8String:[json bytes]]);
来源:https://stackoverflow.com/questions/15324188/why-this-code-with-nsjsonserialization-always-crashes