我正在尝试解析变量中的一个 int 值,但它返回 nil 或 0 我想要的值来自 customer_group_id。我正在使用快速。我已经从 json 文件中解析出其他信息,但在这个阶段它一直在搞砸。
print("My Loyalty rank: " , newJson["loyalty_rank"][0]["customer_group_id"].string)
myRank = newJson["loyalty_rank"][0]["customer_group_id"].intValue
这是json文件
{ "id":298,
"name":"桃子 桜",
"total_points_earned":164,
"points_available_to_spend":164,
"loyalty_rank":{
"customer_group_id":9,
"name":"Baby Bee",
"ratio":1
},
"order_history":[
{ }
],
"barcode_id":"C-00000298"
}
最佳答案
loyalty_rank
是 [String:AnyObject]
意味着它的 Dictionary 不是数组 ...
尝试像这样打印
// if its string
print("My Loyalty rank: " , newJson["loyalty_rank"]["customer_group_id"].string)
// if its Int
print("My Loyalty rank: " , newJson["loyalty_rank"]["customer_group_id"].intValue)
最好使用 if let
或 guard
之类的
if let customerId = newJson["loyalty_rank"]["customer_group_id"].intValue{
// customerId is int value
}
else{
// not an int
}
关于ios - swift 从json中解析出一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38519091/