如何解析json并将其填充到模型中?

Posted

技术标签:

【中文标题】如何解析json并将其填充到模型中?【英文标题】:how to parse json and fill it in model? 【发布时间】:2017-03-20 06:10:04 【问题描述】:

这是我的 json

[
 
    "_id": "58b517e8dd7fe4a90fcadc44",
    "isActive": false,
    "balance": "$1,293.72",
    "picture": "http://placehold.it/32x32",
    "age": 38,
    "eyeColor": "brown",
  "name": "Finch Hayes",
  "gender": "male",
  "company": "NIKUDA",
  "email": "finchhayes@nikuda.com",
  "phone": "+1 (874) 422-3921",
  "address": "227 Trucklemans Lane, Steinhatchee, New Hampshire, 9835",
  "about": "Veniam pariatur exercitation consequat exercitation dolore sint labore consequat enim cupidatat pariatur elit. Anim officia velit aliqua anim consectetur mollit aliquip occaecat duis non. Ea voluptate velit eu elit qui nulla aliquip.\r\n",
  "friends": [
     
        "id": 0,
        "name": "Mooney Bond"
     ,
     
        "id": 1,
        "name": "Rosie Owen"
     ,
     
        "id": 2,
        "name": "Melanie Brown"
       
    ]
 ,
 
  "_id": "58b517e8b53b162133de0013",
  "isActive": true,
  "balance": "$2,637.14",
  "picture": "http://placehold.it/32x32",
  "age": 29,
  "eyeColor": "green",
  "name": "Terry Conway",
  "gender": "male",
  "company": "MEDALERT",
  "email": "terryconway@medalert.com",
  "phone": "+1 (856) 436-2212",
  "address": "904 Carlton Avenue, Carrizo, Nevada, 9560",
  "about": "Aute duis esse enim sit occaecat veniam aute sunt esse. Quis consequat dolore veniam reprehenderit laborum. Labore quis magna cillum consequat laborum amet in amet proident sit.\r\n",
  "friends": [
     
        "id": 0,
        "name": "Sparks Baxter"
     ,
     
        "id": 1,
        "name": "Carrillo Gonzales"
     ,
     
        "id": 2,
        "name": "Hebert Montgomery"
     
  ]
 ]

我已经创建了 person 和 personFriend 对象。下面是我的main.m

NSError *error;

NSString *url_string = [NSString stringWithFormat:@"http://danialm.weebly.com/uploads/1/0/1/5/101578472/people.json"];

NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url_string]];

id personJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

//NSLog(@"item: %@", personJson);

NSMutableArray *personArray = [[NSMutableArray alloc]init];

NSMutableArray *friendArray = [[NSMutableArray alloc]init];

for (NSDictionary *personInfoDict in personJson) 

    Person *person = [[Person alloc] init];

    person.personId = [personInfoDict objectForKey:@"_id"];

    person.about = [personInfoDict objectForKey:@"about"];

    person.address = [personInfoDict objectForKey:@"address"];

    person.age = [[personInfoDict objectForKey:@"age"] doubleValue];

    person.balance = [personInfoDict objectForKey:@"balance"];

    person.company = [personInfoDict objectForKey:@"company"];

    person.email = [personInfoDict objectForKey:@"email"];

    person.eyeColor = [personInfoDict objectForKey:@"eyeColor"];

    person.gender = [personInfoDict objectForKey:@"gender"];

    person.isActive = [[personInfoDict objectForKey:@"isActive"]boolValue];

    person.name = [personInfoDict objectForKey:@"name"];

    person.phone = [personInfoDict objectForKey:@"phone"];

    person.picture = [personInfoDict objectForKey:@"picture"];

    person.friends = [personInfoDict objectForKey:@"friends"];

    for (NSDictionary *friendInfoDict in personInfoDict) 

        PersonFriends *friend = [[PersonFriends alloc]init];

        friend.friendsId = [[friendInfoDict objectForKey:@"id"]doubleValue];

        friend.name = [friendInfoDict objectForKey:@"name"];

        [friendArray addObject: friend];
    

    [personArray addObject:person];

    [personArray addObject:friendArray];


NSLog(@"personArray: %@", personArray);

我不知道如何解析 json 并将其填充到模型中。这是对还是错,因为我在目标 c 开发中仍然是新手。

【问题讨论】:

你研究过 jsonModel 吗? github.com/jsonmodel/jsonmodel 你有没有尝试在 Objective-c 中使用 YYModel 或在 Swift 中使用 HandyJSON thnx 伙计们..供建议..我只想在没有外部框架的情况下手动完成。:) 【参考方案1】:

在大多数情况下,它看起来还不错。几个问题:

您应该将NSMutableArray *friendArray = [[NSMutableArray alloc]init]; 移动到您的第一个for 循环中,就在您要创建朋友对象的第二个for 循环之前。这是因为每个人都有自己的好友列表,所以需要新建一个数组。 for (NSDictionary *friendInfoDict in personInfoDict) 应该是 for (NSDictionary *friendInfoDict in [personInfoDict objectForKey:@"friends"])。否则,您会尝试为每个人创建一个朋友。 person.friends = [personInfoDict objectForKey:@"friends"]; 应该是person.friends = friendArray;,并且应该在你的好友循环之后移动到。 你真的不需要[personArray addObject:friendArray];,因为每个人对象应该已经有一个朋友数组。

此外,这不是问题,而是代码可读性的更多问题 - 但值得将大量代码移动到您的 Person 和 PersonFriend 对象中。这样你的循环就变成了:

for (NSDictionary *personInfoDict in personJson) 

    Person *person = [[Person alloc] initWithDictionary:personInfoDict];
    [personArray addObject:person];

在您的 Person initWithDictionary 中,您将拥有所有代码:

 - (instancetype)initWithDictionary:(NSDictionary *)personInfoDict 
   if (self = [super init]) 
       self.personId = [personInfoDict objectForKey:@"_id"];
       NSMutableArray *friendArray = [[NSMutableArray alloc]init];
       for (NSDictionary *friendInfoDict in [personInfoDict objectForKey:@"friends"]) 

           PersonFriends *friend = [[PersonFriends alloc]initWithDictionary:friendInfoDict];
           [friendArray addObject: friend];
       
       ...etc
    

   return self;

编辑: 要查找特定的人,您可以编写一个辅助方法来遍历您的人员数组并返回具有给定 id 的人员(例如,可以使用名称等):

- (Person *)personWithId:(NSString *)id 
    for (Person *person in self.personArray) 
        if ([person.id isEqualToString:id]) 
            return person;`
        
    
    return nil;

虽然您需要传入您的 personArray 或将其设为属性,以便您的辅助方法可以访问它(最好将其设为属性)。

【讨论】:

thnx @allan ..for 帮我弄清楚..如果我想显示特定人的键值,我该怎么做? 嗯,你有你的 Person 对象数组。您可以循环访问每个人:for (Person *person in personArray) ;。我会用一个帮助方法的例子来更新我的答案来找到一个特定的人:) 哎呀..thnx先生..真的很感激。:)【参考方案2】:

您应该选择非常易于使用的 JSONAccelerator ios 应用程序。 通过它您可以在几秒钟内解析和创建模型。

【讨论】:

以上是关于如何解析json并将其填充到模型中?的主要内容,如果未能解决你的问题,请参考以下文章

使用 Dart 语言解析嵌套 JSON 数组并将其放入模型类中

如何从 json 中获取 int 并将其解析为 dart 中的 bool?

如何拆分/解析 JSON 数据并将其保存到 SQL 服务器中?

Python - 如何解析 JSON 并将其保存到 MYSQL 数据库

解析嵌套的 JSON 并将其保存到 SQLite 中,然后检索它

如何解析json数据并将其加载到django模板