iosobjective-cjsonjsonmodelcustom-object

how to parse json and fill it in model?


this is my 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"
     }
  ]
 }]

I already create person and personFriend object. below this is my 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);

I cannot figure out how to parse json and filled it in model.this is the right way or wrong because im still new in objective c development.


Solution

  • For the most part it looks ok. Couple of issues:

    Also, less of an issue, and more for code readability - but it's worth moving a lot of that code inside your Person and PersonFriend objects. That way your loop becomes:

    for (NSDictionary *personInfoDict in personJson) {
    
        Person *person = [[Person alloc] initWithDictionary:personInfoDict];
        [personArray addObject:person];
    }
    

    And in your Person initWithDictionary you'd have all that code:

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

    Edit: To find a specific person, you can write a helper method to loop through your person array and return a person with a given id (for example, can use name, etc):

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

    Though you would need to either pass your personArray in, or make it a property so you helper method can access it (probably best to make it a property).