现在我有一些api调用的代码。在下面的代码中,“print(httpResponse)
”就是我可以看到我的api中的所有数据。但是在这个JSON
数据中我需要选择一些参数,我需要在我的表视图中显示。怎么做。
let headers = [
"content-type": "application/json",
"cache-control": "no-cache",
"postman-token": "76a32ab0-ade1-d9a6-881f-eff2705178ba"
]
let parameters = [“ID”: "5"]
let postData = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: nil)
var request = NSMutableURLRequest(URL: NSURL(string: "http:EXAMPLEAPI..php")!,
cachePolicy: .UseProtocolCachePolicy,
timeoutInterval: 10.0)
request.HTTPMethod = "POST"
request.allHTTPHeaderFields = headers
request.HTTPBody = postData
let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? NSHTTPURLResponse
print(httpResponse)
}
})
dataTask.resume()
我的JSON结构和数据:
{
"status": 1,
"message": "Received Orders.",
"myorders": [
{
"orderID": "1",
"orderStatus": "Pending",
"orderPrice": "450",
"dateAdded": "01",
"monthAdded": "Jan"
},
{
"orderID": "2",
"orderStatus": "Pending",
"orderPrice": "1400",
"dateAdded": "01",
"monthAdded": "Jan"
}
]
}
在我的表格视图中,我需要显示,订单ID,状态,价格。如何在某些nsarray
或nsstring
中保存api响应数据,并与我的表格视图标签保持一致。
请帮帮我。感谢
答案 0 :(得分:2)
可以使用数据模型轻松完成
第1步: - 创建NSObject类
#import <Foundation/Foundation.h>
@interface Items : NSObject
@property (strong, nonatomic) NSString * orderID;
@property (strong, nonatomic) NSString * orderStatus;
@property (strong, nonatomic) NSString * orderPrice;
@property (strong, nonatomic) NSString * dateAdded;
@property (strong, nonatomic) NSString * monthAdded;
@end
第2步: - 将json数组中的值添加到创建的数据模型中。
//Create a method
-(void)getData{
<==Your JSON Code for parsing==>
//get your data according to you in dictionary from your nested array.
for (NSDictionary *dict in self.arrOfJsonData) {
Items *itemData = [[Items alloc] init];
itemData.orderId=dict[@"orderId"];
itemData.orderStatus=dict[@"orderStatus"];
itemData.orderPrice=dict[@"orderPrice"];
itemData.dateAdded=dict[@"dateAdded"];
itemData.monthAdded=dict[@"monthAdded"];
[self.nsmutableArray addObject:itemData];//Add the object in an NSMutableArray
itemData=nil;
}
}
第3步: -
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
Items *item = self.nsmutableArray[indexPath.row];//Get according to your JSON array.
cell.lblorderID.text=item.orderID;
cell.lblorderStatus.text=item.orderStatus;
cell.lblorderPrice.text=item.orderPrice;
cell.lbldateAdded.text=item.dateAdded;
return cell;
}
答案 1 :(得分:0)
我在这里采取了你的JSON
并解析了下面提到的数据
第1步:获得回复后,使用NSJSONSerialization
以Array
和Dictionary
格式获取JSON。在你的情况下,响应返回字典,我们可以从中获取myOrder数组。
第2步:遍历myOrder数组并将数据放入模型对象中。或者你可以保持原样(即Dictionary
格式)并保留在表数据源数组中。
第3步:从cellForRowAtIndexPath
的数据源数组中获取词典或模型对象,并将文本分配给标签。
代码段:
let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? NSHTTPURLResponse
//Call the method to parse
getLocalJsonData(data);
print(httpResponse)
}
})
func getLocalJsonData(data:NSData)
{
var jsonMyOrder : NSArray!
var jsonTemp : NSDictionary = NSDictionary()
do{
jsonTemp = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableLeaves) as! NSDictionary;
}catch{
}
print("jsonTemp \(jsonTemp)");
jsonMyOrder = jsonTemp["myorders"] as! NSArray;
print("json \(jsonMyOrder)");
for dictTemp in jsonMyOrder
{
print("oredr id \(dictTemp["orderID"])");
print("Status id \(dictTemp["orderStatus"])");
print("Price id \(dictTemp["orderPrice"])");
}
//Take a global variable NSMUtableArray type and add the parse order array to access it in the table's delegate method
arrEvents = NSMutableArray(array: json);
tblView.reloadData();
}
代码CellForRowAtIndexPath
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let reuseIdentifier = "receipeID";
let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier) as! ReceipeTableCell;
let dictOrder = arrEvents[indexPath.row];
let order = dictOrder["orderID"] as? String;
let status = dictOrder["orderStatus"] as? String;
let price = dictOrder["orderPrice"] as? String;
cell.lblIngrediants.text = NSString(format: "Order : %@", order!) as String;
cell.lblRatingsValue.text = NSString(format: "Status : %@", status!) as String;
cell.lblRatings.text = NSString(format: "Price : %@", price!) as String;
return cell;
}
输出:
希望它有所帮助 快乐的编码...