我正在尝试解析NSArray
,JSON
但出现以下错误:
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM JSONRepresentation]: unrecognized selector sent to instance 0xa93e460' * First throw call stack: (0x21f1012 0x1feae7e 0x227c4bd 0x21e0bbc 0x21e094e 0x3445a 0x33ecc 0x26a453f 0x26b6014 0x26a72e8 0x26a7450 0x95e22e12 0x95e0acca) libc+ +abi.dylib: 终止调用抛出异常
我已经包含了SBJson_3.1.1/Classes目录中的所有类。
这是代码:
NSMutableArray* arr = ...get array
NSString* jsonArr = [arr JSONRepresentation]; // here I get error
当我在简单字符串数组中执行此操作时,它可以工作:
NSData *jsonData = [NSJSONSerialization arr
options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
但我的数组包含对象列表(人)可能有问题。
我使用 Item 而不是 person 就像示例
Item.h
@interface Item : NSObject
{
BOOL IsOpen;
NSString* Description;
}
@property int ItemId;
@property int SequenceId;
@property BOOL IsOpen;
@property NSString* Description;
- (id) proxyForJson;
@end
项目.m
@implementation Item
@synthesize ItemId;
@synthesize SequenceId;
@synthesize Description;
@synthesize IsOpen;
- (id) proxyForJson {
return [NSDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:@"%i", ItemId], @"ItemId",
SequenceId, @"SequenceId",
Description, @"Description",
IsScanned, @"IsOpen",
nil ];
}
@end
更新
学生示例
我尝试制作一个单独的项目。我从 sbjson 框架的 classes 目录中复制到新项目中。这是代码:
#import "SBJson.h"
@interface Student : NSObject
{
NSString *name;
NSInteger sid;
NSString *email;
}
@property NSString *name;
@property NSInteger sid;
@property NSString *email;
- (id) proxyForJson;
@end
@implementation Student
@synthesize name;
@synthesize sid;
@synthesize email;
- (id) proxyForJson{
return [NSDictionary dictionaryWithObjectsAndKeys:
name, @"student_name",
[NSNumber numberWithInt:sid], @"student_id",
email, @"email",
nil ];
}
@end
NSMutableArray* studentArray = [[NSMutableArray alloc]init];
Student* s1 = [[Student alloc]init];
s1.name = @"student 1";
s1.sid = 45;
s1.email = @"test@test.com";
Student* s2 = [[Student alloc]init];
s2.name = @"student 2";
s2.sid = 46;
s2.email = @"plavi@test.com";
[studentArray addObject:s1];
[studentArray addObject:s2];
NSString *jsonString = [studentArray JSONRepresentation];
NSLog(@"%@", jsonString);
我再次收到错误:
由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[__NSArrayM JSONRepresentation]:无法识别的选择器发送到实例 0x741b100”