简体   繁体   English

如何使用 json 个对象的数组初始化 JSONModel?

[英]How to init a JSONModel with an Array of json objects?

I have a model using JSONModel in my objective c application.我有一个 model 在我的目标 c 应用程序中使用 JSONModel。 JSONModel github I am trying init my model from a response of server. JSONModel github我正在尝试从服务器的响应中初始化我的 model。 The response of server is this:服务器的响应是这样的:

[ { "id": 0, "name": "Jhon" }, { "id": 1, "name": "Mike" }, { "id": 2, "name": "Lua" } ] [ { "id": 0, "name": "Jhon" }, { "id": 1, "name": "Mike" }, { "id": 2, "name": "Lua" } ]

My JSONModel is:我的 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

And I'm trying init this then get the response from server like:我正在尝试初始化它然后从服务器获取响应,例如:

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

But I'm getting a null model.但我得到一个 null model。

I think that the problem is the format response like我认为问题在于格式响应,例如

[{ }] [{}]

But I don't know how to convert this.但我不知道如何转换它。

is possible init a JSONModel from an array of json objects?是否可以从 json 个对象的数组中初始化一个 JSONModel?

How can I do this?我怎样才能做到这一点?

The library you reference appears to only be compatible with an NSDictionary root Json object, whereas you have an NSArray root json object. 您引用的库似乎只与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#L123

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

If you check the error returned when attempting to initWithData, I'm sure it will have this error message: 如果您在尝试initWithData时检查返回的错误,我确定它会出现以下错误消息:

Invalid JSON data: Attempt to initialize JSONModel object using initWithDictionary:error: but the dictionary parameter was not an 'NSDictionary'. 无效的JSON数据:尝试使用initWithDictionary初始化JSONModel对象:error:但是dictionary参数不是'NSDictionary'。

Your currently server JSON response: 您当前的服务器JSON响应:

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

An example of what the JSON would look like that the JSONModel lib would be able to parse: JSON看起来像JSONModel lib能够解析的示例:

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

If you're unable to modify your server response on the backend to have it return an NSDictionary as the root JSON object, you could pre-process the returned data to format for what JSONModel lib is expecting (NSDictionary root). 如果您无法在后端修改服务器响应以使其返回NSDictionary作为根JSON对象,则可以预处理返回的数据以格式化JSONModel lib期望的内容(NSDictionary根目录)。

Here's an example of what I mean (specifically you'll want to use something like jsonDataUsingYourCurrentArrayStructureWithPreProcessing: to pre-process your JSON data: 这是我的意思的一个例子(特别是你想要使用像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;
    }
}

Alternatively, you can just roll your own initialization from the JSON array, something along these lines in the People Class: 或者,您可以从JSON数组中滚动自己的初始化,类似于People Class中的这些行:

+ (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];
}

Maybe a bit too late, but just for future readers.也许有点太晚了,但只是为了未来的读者。 JSONModel has specific methods for that: JSONModel 有特定的方法:

  • arrayOfModelsFromDictionaries arrayOfModelsFromDictionaries
  • arrayOfModelsFromData arrayOfModelsFromData
  • arrayOfModelsFromString arrayOfModelsFromString

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

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

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