【问题标题】:How to init a JSONModel with an Array of json objects?如何使用 json 对象数组初始化 JSONModel?
【发布时间】:2019-05-19 21:08:40
【问题描述】:

我的目标 c 应用程序中有一个使用 JSONModel 的模型。 JSONModel github 我正在尝试从服务器的响应中初始化我的模型。服务器的响应是这样的:

[ { “身份证”:0, “名称”:“约翰” }, { “身份证”:1, “姓名”:“迈克” }, { “身份证”:2, “名称”:“Lua” } ]

我的 JSONModel 是:

@protocol People @end

@interface People : JSONModel

@property (nonatomic, strong)  NSArray <Person> * peopleArray;

@end





@protocol Person @end

@interface Person : JSONModel

@property (nonatomic, strong)  NSNumber <Optional>  * id;

@property (nonatomic, strong)  NSString <Optional>  * name;

@end

我正在尝试初始化,然后从服务器获取响应,例如:

NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseData options:NSJSONWritingPrettyPrinted error:&error];
People *peoplemodel = [[People alloc] initWithData:jsonData error:&error];

但我得到的是一个空模型。

我认为问题是像

这样的格式响应

[{ }]

但我不知道如何转换它。

是否可以从 json 对象数组中初始化 JSONModel?

我该怎么做?

【问题讨论】:

标签: arrays objective-c json jsonmodel


【解决方案1】:

您引用的库似乎只与 NSDictionary 根 Json 对象兼容,而您有一个 NSArray 根 json 对象。

https://github.com/jsonmodel/jsonmodel/blob/master/JSONModel/JSONModel/JSONModel.m#L123

https://github.com/jsonmodel/jsonmodel/blob/master/JSONModel/JSONModel/JSONModel.m#L161

如果您在尝试 initWithData 时检查返回的错误,我确定它会出现以下错误消息:

无效的 JSON 数据:尝试使用 initWithDictionary 初始化 JSONModel 对象:错误:但字典参数不是“NSDictionary”。

您当前的服务器 JSON 响应:

NSArray <NSDictionary *> *jsonArray = @[ @{ @"id": @(0), @"name": @"Jhon" }, @{ @"id": @(1), @"name": @"Mike" }, @{ @"id": @(2), @"name": @"Lua" } ];

JSONModel 库能够解析的 JSON 外观示例:

NSDictionary <NSString *, NSArray <NSDictionary *> *> *jsonDictionary = @{ @"peopleArray": @[@{@"id": @(0), @"name": @"Jhon"}, @{ @"id": @(1), @"name": @"Mike" }, @{ @"id": @(2), @"name": @"Lua" }]};

如果您无法在后端修改服务器响应以使其返回 NSDictionary 作为根 JSON 对象,您可以预处理返回的数据以格式化 JSONModel 库所期望的格式(NSDictionary 根)。

这是我的意思的一个例子(特别是你会想要使用类似jsonDataUsingYourCurrentArrayStructureWithPreProcessing: 的东西来预处理你的 JSON 数据:

- (void)viewDidLoad {
    [super viewDidLoad];
    NSArray <NSDictionary *> *jsonArray = @[ @{ @"id": @(0), @"name": @"Jhon" }, @{ @"id": @(1), @"name": @"Mike" }, @{ @"id": @(2), @"name": @"Lua" } ];
    NSError *jsonSerializationError;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonArray options:0 error:&jsonSerializationError];
    if (jsonSerializationError) {
        NSLog(@"jsonSerializationError = %@", jsonSerializationError);
    }
    jsonData = [self jsonDataUsingYourCurrentArrayStructureWithPreProcessing:jsonData];
    NSError *jsonModelError;
    People *people = [[People alloc] initWithData:jsonData error:&jsonModelError];
    if (people) {
        [self printPeople:people];
    } else if (jsonModelError != nil) {
        NSLog(@"Error returned from jsonModel = %@", jsonModelError);
    }
}

- (void)printPeople:(People *)people {
    for (Person *person in people.peopleArray) {
        NSLog(@"person id = %li, name = %@", [person.id integerValue], person.name);
    }
}

- (NSData *)jsonDataUsingYourCurrentArrayStructureWithPreProcessing:(NSData *)jsonData {
    NSError *parsingError;
    id obj = [NSJSONSerialization JSONObjectWithData:jsonData
                                             options:0
                                               error:&parsingError];
    if ([obj isKindOfClass:[NSArray class]] && parsingError == nil) {
        NSArray <NSDictionary *> *jsonArray = (NSArray <NSDictionary *> *)obj;
        NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObject:jsonArray forKey:@"peopleArray"];
        NSError *jsonSerializationError;
        NSData *jsonDictData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:&jsonSerializationError];
        if (jsonDictData && jsonSerializationError == nil) {
            return jsonDictData;
        } else {
            NSLog(@"jsonSerializationError = %@", jsonSerializationError);
            return nil;
        }
    } else {
        if (parsingError) {
            NSLog(@"Error parsing jsonData = %@", parsingError);
        }
        return nil;
    }
}

或者,您可以从 JSON 数组中滚动您自己的初始化,在 People 类中按照以下方式进行:

+ (instancetype)peopleWithJsonArray:(NSArray<NSDictionary *> *)jsonArray {
    People *people = [[People alloc] init];
    if (people) {
        [people setupPeopleArrayFromJsonArray:jsonArray];
    }
    return people;
}

- (void)setupPeopleArrayFromJsonArray:(NSArray <NSDictionary *> *)jsonArray {
    NSMutableArray <Person *> *people = [[NSMutableArray alloc] initWithCapacity:jsonArray.count];
    for (NSDictionary *personDictionary in jsonArray) {
        Person *person = [Person personWithID:[personDictionary objectForKey:@"id"] andName:[personDictionary objectForKey:@"name"]];
        [people addObject:person];
    }
    self.peopleArray = [NSArray arrayWithArray:people];
}

【讨论】:

    【解决方案2】:

    也许有点太晚了,但只是为了未来的读者。 JSONModel 有专门的方法:

    • arrayOfModelsFromDictionaries
    • arrayOfModelsFromData
    • arrayOfModelsFromString

    https://github.com/jsonmodel/jsonmodel/blob/master/JSONModel/JSONModel/JSONModel.m#L1055

    【讨论】:

      猜你喜欢
      • 2014-05-18
      • 1970-01-01
      • 2020-04-21
      • 2016-03-11
      • 1970-01-01
      • 1970-01-01
      • 2013-02-04
      • 1970-01-01
      相关资源
      最近更新 更多