Question

I'm receiving a JSON payload of data from a MVC API in my iOS application. NSJSONSerialization then serializes this into an object. This object contains some properties and also a list of data objects. The data objects are of type NSDictionary. I already have the class structure of these objects in ObjC (Im using odata so i want to convert the objects to their OdataObject equivalent).

So I'd like to know how I can cast/convert these NSDictionary objects to their corresponding OdataObject class (or any object really)?

Was it helpful?

Solution

You can't cast an NSDictionary instance to be an OdataObject, you either need to explicitly convert the instance or create the appropriate instance when you deserialise the JSON.

You could look at using setValuesForKeysWithDictionary: to push your dictionary contents into another instance using KVC. Whether this will work in this case depends on the OdataObject definition (from github? Not convinced) and the dictionary contents...

OTHER TIPS

Write a class category for NSDictionary that allows the conversion to the OdataObject class? I'm sorry, I don't completely understand what you're asking but if you need to be able to convert NSDictionary to a custom object, then I recommend Class Categories:

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/CustomizingExistingClasses/CustomizingExistingClasses.html

Yes, you can not cast your NSDictionary instance to your custom model object. For that you need to write code of conversion.

1) Create a class which inherits NSObject with required properties.
2) Synthesize all the properties
3) Write one private keyMapping method which returns the dictionary with keys you want in your model object as

-(NSDictionary *)keyMapping {

    return [[NSDictionary alloc] initWithObjectsAndKeys:
            @"key1", @"key1",
            @"key2", @"key2",
            @"key3", @"key3",
            @"key4", @"key4",
            @"key5", @"key5",
            nil];
}

4) Write class method which takes NSDictionary instance, as a parameter and returns instance of the same model class with filled values from NSDictionary as (Pass your dictionary to this method)

+(ModelClass *)getModelClassObjectFromDictionary:(NSDictionary *)dictionary {

    ModelClass *obj = [[ModelClass alloc] init];
    NSDictionary *mapping = [obj jsonMapping];

    for (NSString *attribute in [mapping allKeys]){

        NSString *classProperty = [mapping objectForKey:attribute];
        NSString *attributeValue = [dictionary objectForKey:attribute];

        if (attributeValue!=nil&&!([attributeValue isKindOfClass:[NSNull class]])) {

            [obj setValue:attributeValue forKeyPath:classProperty];
        }
    }

    return obj;

}

Thats it. Hope this helps you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top