IOS / Objective-C:将JSON转换为Object时出错

时间:2015-10-18 16:45:58

标签: ios json kvc

我正在尝试将JSON数组转换为对象以在表中显示。我能够捕获JSON。但是,当我尝试变成对象时,我会收到如下错误。肯定有一个名为" name"在对象类中。

- (void)fetchedData:(NSData *)responseData {
    NSError* error;
    NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData 
                                                         options:kNilOptions
                                                           error:&error];
    NSMutableArray* latestItems = nil;
    latestItems = [[NSMutableArray alloc] init];
    latestItems = [json objectForKey:@"items"];
    [self.tableView reloadData];
    for (int i = 0; i < latestItems.count; i++)
    {
        NSDictionary *itemElement = latestItems[i];
        // Create a new l object and set its props to todoElement properties
        IDItemFromServer *newItem = [[IDItemFromServer alloc] init];
//ERROR  NEXT LINE THROWS FOLLOWING ERROR
//'NSUnknownKeyException', reason: '[<IDItemFromServer 0x14e88010> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key name.'
       [newItem setValue:@"hi" forKey:@"name"];
       [newItem setValue:itemElement[@"address"] forKey:@"address"];

        // Add this new item  to the array
        [latestItems addObject:newItem];
    }

欢迎任何有关如何修复错误的建议。

编辑:

//Object.h file
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>


@interface IDItemFromServer : NSObject
@property (nonatomic, retain) NSNumber * iid;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSString * address;

@end

1 个答案:

答案 0 :(得分:1)

它表示 IDItemFromServer 没有属性名称。添加名称,地址属性,如下面的代码

In IDItemFromServer.h file

#import <Foundation/Foundation.h>
@interface IDItemFromServer : NSObject

@property(nonatomic,strong) NSString name;
@property(nonatomic,strong) NSString address;

@end

在IDItemFromServer.m文件中

#import "IDItemFromServer.h"

@implementation IDItemFromServer

@synthesize name;
@synthesize address;

@end