将NSDictionary数据放在ModelObject中

时间:2014-06-25 19:25:31

标签: ios iphone objective-c

我收到一个JSON对象(转换为NSDictionary),我想将它放入我的模型对象中。

我试过这个

  {
        Description = "Desc.";
        EndTime = "2014-06-25T05:35:00";
        Id = "";
        IsActive = 1;
        StartTime = "2014-06-25T05:30:00";
        Title = "Test appointment";
    },
        {
        Description = Qww;
        EndTime = "2014-06-26T02:58:00";
        Id = "";
        IsActive = 1;
        StartTime = "2014-06-26T01:58:00";
        Title = q;
    }

我想将它存储到我的模型对象NSobject中。但只能获得第一个dictioanry

我试过这个

     MyAppoinmentModel * modelObj;

    modelObj =[[MyAppoinmentModel alloc]init];

modelobj = [[MyAppoinmentModel alloc] init];

    for(NSMutableDictionary * dic in array)
    {

        NSString * strTitle =[dic valueForKey:@"Title"];
        NSString * strDescription =[dic valueForKey:@"Description"];
        NSString * strStartTime =[dic valueForKey:@"StartTime"];
        NSString * strEndTime =[dic valueForKey:@"EndTime"];
        NSString * strMeetingDate =[dic valueForKey:@"MeetingDate"];
        NSString * strIsActive =[dic valueForKey:@"IsActive"];


        modelobj.Titlestr=strTitle;
        modelobj.Descriptionstr=strDescription;
        modelobj.StartTimeStr=strStartTime;
        modelobj.EndTimeStr=strEndTime;
        modelobj.Daystr=strMeetingDate;

    }

我可能错在哪里帮你做这个。

1 个答案:

答案 0 :(得分:0)

这是应该有用的代码。我不知道keyObjects上方的关键是什么(如果你想要代码样本响应,请包括下一次)所以我只是假设它是“模型”。

我正在将所有modelObj添加到NSMutableArray,以便您可以访问所有modelObj个后缀,因为无法保证只有一个NSDictionary在JSON返回中。这使用Hot Licks建议创建一个方法来创建每个MyAppointmentModel

注意:您忘记了IsActive和ID部件。我已经在我的解决方案中存根了,但你应该将它们添加到你的代码中。

  NSArray* jsonSerialArray = [NSJSONSerialization
         JSONObjectWithData:jsonResponse
         options:0
         error:&error];

  NSArray *JSON = [jsonSerialArray objectForKey:@"models"];
  NSMutableArray *modelObjArray = [NSMutableArray array];

  for (NSDictionary *dict in JSON)
  {      
    [modelObjArray addObject:[self createModelObjectWithDictionary:dict]];
  }
  do something with modelObjArray
}

-(MyAppointmentModel *)createModelObjectWithDictionary:(NSDictionary *)dict
{
  MyAppoinmentModel *modelObj = [[MyAppoinmentModel alloc] init];    

  modelobj.Titlestr=[dict valueForKey:@"Title"];
  modelobj.Descriptionstr=[dict valueForKey:@"Description"];
  modelobj.StartTimeStr=[dict valueForKey:@"StartTime"];
  modelobj.EndTimeStr=[dict valueForKey:@"EndTime"];
  modelobj.MeetingDate=[dict valueForKey:@"MeetingDate"];
  modelobj.IsActive=[dict valueForKey:@"IsActive"];
  modelobj.ID=[dict valueForKey:@"ID"];

  return modelobj;
}