Parsing a JSON string to an object based on a class in iOS

234 Views Asked by At

I would like to map a json string to an anonymous object using the specific class. Suppose i have a country class. I would like to parse a json string into this object without knowing which object it is. So i use the class for parsing.

@interface CountryModel 

@property (assign, nonatomic) int id;
@property (strong, nonatomic) NSString* country;

@end

NSString* json = (fetch here JSON from Internet) ... 
CountryModel* country ;
id obj =  country ;

obj = tojson( [obj class] , json  )

https://github.com/icanzilb/JSONModel does what i need but i need same thing without using the inheritance. I would like to do same thing without inheriting from JSONModel;

1

There are 1 best solutions below

0
On

You could define a Category for your custom model class (say, CountryModel) which implements a class factory method. A contrived example:

@interface CountryModel (JSONExtension)
+ (CountryModel*) jsonExtension_modelWithJSONObject:(NSDictionary*)jsonObject error:(NSError**)error;
@end


@implementation CountryModel (JSONExtension)

+ (CountryModel*) jsonExtension_modelWithJSONObject:(NSDictionary*)jsonObject error:(NSError**)error {        
    // Create an object of type Foo with the given NSDictionary object
    CountryModel* result = [[CountryModel alloc] initWithName:jsonObject[@"name"]];
    if (result == nil) {
        if (error) {
            *error = [NSError errorWithDomain:@"CountryModel" 
                                         code:-100
                                     userInfo:@{NSLocalizedDescriptionKey: @"Could not initialize CountryModel with JSON Object"}];
        }
        return nil;
    }
    // "recursively" use jsonExtension_modelWithJSONObject:error: in order to initialize internal objects:
    BarModel* bar = [BarModel jsonExtension_modelWithJSONObject:jsonObject[@"bar"] error:error];
    if (bar == nil) // bar is required
    {
        result = nil;
        return nil;
    }
    result.bar = bar;

    return result;
}

@end

jsonObject is a representation of a JSON Object as a NSDictionary object. You need to first create this representation before passing it the class factory method, e.g.:

NSError* error;
NSDictionary* jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
assert([jsonObject isKindOfClass[NSDictionary class]]);

CountryModel* model = [CountryModel jsonExtension_modelWithJSONObject:jsonObject error:&error];