2017-08-01 78 views
0

我有以下json responseObject數組。我可以得到orderiddatetime屬性。如何處理JSON對象中的對象

但是,我不知道如何能夠處理json中的products對象。

如果您有任何建議,意見或建議,我將不勝感激。

這裏是JSON responseObject

[ 
    { 
    "orderid": "1", 
    "datetime": "2017-07-29 23:31:53", 
    "products": [ 
     { 
     "productid": "2", 
     "productname": "Beef Kabob", 
     } 
    ] 
    }, 
    { 
    "orderid": "2", 
    "datetime": "2017-07-30 05:18:41", 
    "products": [ 
     { 
     "productid": "1", 
     "productname": "Baked Chicken", 
     } 
    ] 
    } 
] 

ViewController.m - 從URL中檢索數據

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; 
[manager GET:AppConstant.getAllOrdersURL parameters:nil progress: nil success:^(NSURLSessionTask * _Nonnull operation, id responseObject) 
{ 
    // retrieve and store them in the mutable array 
    for (id jsonItem in responseObject) 
    { 
     OrderData *orderItem = [[OrderData alloc]initWithDictionary:jsonItem]; 
     [self.orderElements addObject:orderItem]; 
    } 
} 
failure:^(NSURLSessionDataTask * _Nullable operation, NSError * _Nonnull error) { 

}]; 

OrderData.m

-(id)initWithDictionary:(NSDictionary *)orderDict 
{ 
    self = [self init]; 
    if (self) 
    { 
     self.datetime = [orderDict objectForKey:@"datetime"]; 
     self.orderid = [orderDict objectForKey:@"orderid"]; 
    } 
    return self; 
} 
+1

爲包含屬性productID和另一個productName的Product創建一個類。向您的'OrderData'類中添加一個NSArray屬性,以將這些產品添加到它。 – Larme

回答

1

在你OrderData你需要添加一個類型的NSArray的productsArr屬性,則在initWithDictionary:

self.productsArr = [[NSArray alloc] initWithArray:[orderDict objectForKey:@"products"]]; 
-1

你的JSON可能包含很多productidproductnameorderDict在包含字典的陣列產品,以便進行迭代。

self.productArray = [NSArray alloc] initWithArray:[orderDict [email protected]:@"products"]];