【问题标题】:Parsing a JSON string to an object based on a class in iOS基于iOS中的类将JSON字符串解析为对象
【发布时间】:2013-12-23 13:55:53
【问题描述】:

我想使用特定类将 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 的情况下做同样的事情;

【问题讨论】:

    标签: ios json class generics jsonmodel


    【解决方案1】:

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

    @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];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-12
      • 1970-01-01
      • 1970-01-01
      • 2019-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-14
      相关资源
      最近更新 更多