繁体   English   中英

根据iOS中的类将JSON字符串解析为对象

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

我想使用特定的类将json字符串映射到匿名对象。 假设我有一个国家班。 我想将json字符串解析为该对象,而不知道它是哪个对象。 因此,我使用该类进行解析。

@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可以满足我的需要,但我需要使用继承而不需要继承。 我想做同样的事情而不继承自JSONModel;

您可以为实现类工厂方法的自定义模型类(例如CountryModel )定义一个Category。 一个人为的例子:

@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是JSON对象作为NSDictionary对象的表示。 您需要先创建此表示形式,然后再将其传递给类工厂方法,例如:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM