簡體   English   中英

如何解析json並將其填入模型中?

[英]how to parse json and fill it in model?

這是我的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對象。 下面這是我的主要內容

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開發中仍然是新的。

在大多數情況下它看起來不錯。 幾個問題:

  • 你應該移動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,或者讓它成為一個屬性,所以你幫助方法可以訪問它(可能最好使它成為一個屬性)。

您應該使用非常容易使用的JSONAccelerator iOS應用程序。 您可以在幾秒鍾內解析並創建模型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM