我的json数据中有以下参数。
date = "2018-02-12";
"grand_total" = "82.88";
message = "Order Details Details";
status = "order_details";
"sub_total" = 74;
"tax_total" = "8.880000000000001";
time = "06:53:46";
如何设置标签的总计和小计。在目标c中,我们可以使用带有格式的nsstring字符串直接访问字符串的任何值,但在swift中没有这样的选项。
答案 0 :(得分:1)
您需要首先将json解析为对象,然后访问您要使用的数据:
if let object = json as? [String:Any] {
if let total = object["grand_total"] as? Double, let subTotal = object["sub_total"] as? Double {
// You can now use total and subTotal in here now to set to your labels
totalLabel.text = "\(total)"
subTotalLabel.text = "\(subTotal)"
}
}
答案 1 :(得分:1)
Swift 3
使用if let
将是最安全的方式。
if let gTotal = dict["grand_total"] as? Double {
// gTotal had the double value
}
else if let gTotal = dict["grand_total"] as? Int {
// gTotal had the int value
}
else {
// not double nor int value.
}
if let subTotal = dict["sub_total"] as? Double {
// subTotal had the double value
}
else if let subTotal = dict["sub_total"] as? Int {
// subTotal had the int value
}
else {
// not double nor int value.
}
if let message = dict["message"] as? String {
// message had the string value
}
else {
// not string value
}
希望它有所帮助。