Search code examples
iosjsonkvc

IOS/Objective-C: Error Converting JSON to Object


I am trying to convert JSON array to object for display in table. I am able to capture JSON. However, when I try to turn into object, I get error shown below. There is definitely a property named "name" in object class.

- (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];
    }

Would appreciate any suggestions on how to fix error.

Edit:

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

Solution

  • It says IDItemFromServer has no property name. add the name,address property like bellow code

    In IDItemFromServer.h file
    
    #import <Foundation/Foundation.h>
    @interface IDItemFromServer : NSObject
    
    @property(nonatomic,strong) NSString name;
    @property(nonatomic,strong) NSString address;
    
    @end
    

    In IDItemFromServer.m file

    #import "IDItemFromServer.h"
    
    @implementation IDItemFromServer
    
    @synthesize name;
    @synthesize address;
    
    @end