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

时间:2018-03-22 18:17:26

标签: json swift alamofire

    {
  "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)
}

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

在nutrition数据方法中,我尝试使用.responseJSON但是它抛出了一个错误,所以我切换到了.responseString。我想从该JSON获取“totalNutrients”信息。帮助将不胜感激

3 个答案:

答案 0 :(得分:0)

最好使用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"])
      }


  }

然后尝试

答案 1 :(得分:0)

Ary alamofire.response,然后直接将数据解析为JSON

 Alamofire.request(url, method: .get).response { response in
   if response.result.isSuccess {
     let nutritionJSON : JSON = JSON(response.data)
     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)
} 

答案 2 :(得分:0)

如果您只想序列化JSON,那么绝对应该使用responseJSON()。如果您尝试将其与Decodable对象一起使用,则应使用responseData()并使用数据解码其中一个自定义类型。始终验证。

func getNutritionData(url: String) {

Alamofire.request(url)
    .validate(statusCode: 200...200)
    .validate(contentType: ["application/json"])

    .responseJSON { (response) in
        switch response.result {
        case .success(let json):
            // Do something with the json.

            let dict = json as? [String: Any]
            print(dict["<KEY>"]!)

        case .failure(let error):

            print(error)
        }

    }

}