gpt4 book ai didi

json - 如何使用 Alamofire 和 Swift 4.0 从 JSON 获取值?

转载 作者:行者123 更新时间:2023-11-30 11:39:10 27 4
gpt4 key购买 nike

    {
"uri" : "http://www.edamam.com/ontologies/edamam.owl#recipe_f9e656dd9d2b4db9816340687d01722c",
"calories" : 38,
"totalWeight" : 113.25,
"dietLabels" : [ "LOW_FAT" ],
"healthLabels" : [ "SUGAR_CONSCIOUS", "VEGAN", "VEGETARIAN", "PEANUT_FREE", "TREE_NUT_FREE", "ALCOHOL_FREE" ],
"cautions" : [ ],
"totalNutrients" : {
"ENERC_KCAL" : {
"label" : "Energy",
"quantity" : 38.505,
"unit" : "kcal"
},
"FAT" : {
"label" : "Fat",
"quantity" : 0.41902500000000004,
"unit" : "g"
},
"FASAT" : {
"label" : "Saturated",
"quantity" : 0.044167500000000005,
"unit" : "g"
},
"FAMS" : {
"label" : "Monounsaturated",
"quantity" : 0.0124575,
"unit" : "g"
},
"FAPU" : {
"label" : "Polyunsaturated",
"quantity" : 0.043035000000000004,
"unit" : "g"
}
}

}

/** 联网方式*/

   func getNutritionData(url: String) {
Alamofire.request(url, method: .get)
.responseString { response in
if response.result.isSuccess {

print("Sucess! Got the Nutrition data")
let nutritionJSON : JSON = JSON(response.result.value!)
//print(nutritionJSON)
self.updateNutritionData(json: nutritionJSON)

} else {
print("Error: \(String(describing: response.result.error))")
self.caloriesLable.text = "Connection Issues"
}
}
}



func updateNutritionData(json: JSON) {
let calories = json["calories"].intValue
print(calories)
}

^ 例如,当我尝试获取卡路里时,我得到了零

在 NutritionData 方法中,我尝试使用 .responseJSON 但它抛出错误,因此我切换到 .responseString。我想从该 JSON 中获取“totalNutrients”信息。如有帮助,我们将不胜感激

最佳答案

最好使用带有 responseJSON 的方法,而不是 responseString

Alamofire.request(url, method: .get, parameters:nil, encoding: JSONEncoding.default).responseJSON { response in
print(response)

if let json = response.result.value as? [String:Any] {
print(json["calories"])
}


}

然后尝试

关于json - 如何使用 Alamofire 和 Swift 4.0 从 JSON 获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49435807/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com