且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将JSON字符串解析为对象数组Objective C

更新时间:2023-01-17 13:18:56

我建议为 Restaurant 类实现一个init方法。

I would suggest to implement an init method for your Restaurant class.

-(instancetype) initWithParameters:(NSDictionary*)parameters
{
    self = [super init];
    if (self) {
        //initializations
        _validationCode = parameters[@"validationCode"]; // may be NSNull
        _firstName = [parameters[@"FirstName"] isKindOfClass:[NSNull class]] ? @"" 
                     : parameters[@"FirstName"];
        ...
    }
    return self;
}

注意:你可能有JSON Null的事实,使你的初始化有点阐述。当相应的JSON值为Null时,您需要决定如何初始化属性。

Note: the fact that you may have JSON Nulls, makes your initialization a bit elaborate. You need to decide how you want to initialize a property, when the corresponding JSON value is Null.

您的参数 dictionary将是来自服务器的JSON数组的第一级字典。

Your parameters dictionary will be the first level dictionary from the JSON Array which you got from the server.

首先,创建一个JSON表示,即JSON中的NSArray对象: / p>

First, create a JSON representation, that is a NSArray object from the JSON:

NSError* localError;
id restaurantsObjects = [NSJSONSerialization JSONObjectWithData:data 
                                                        options:0 
                                                          error:&localError];

IFF这没有失败,你的 restaurantsObjects 现在应该是 NSArray 对象,其中包含餐馆 NSDictionary s。

IFF this did not fail, your restaurantsObjects should now be an NSArray object containing the restaurants as NSDictionarys.

现在,可以直接创建一个 NSMutableArray ,它将填充 Restaurant 对象:

Now, it will be straight forward to create a NSMutableArray which will be populated with Restaurant objects:

NSMutableArray* restaurants = [[NSMutableArray alloc] init];
for (NSDictionary* restaurantParameters in restaurantsObjects) {
    Restaurant* restaurant = [Restaurant alloc] initWithParameters: restaurantParameters];
    [restaurants addObject:restaurant];
}

最后,您可以设置一个属性餐馆在某些控制器中:

and finally, you may set a property restaurants in some controller:

self.restaurants = [restaurants copy];