简体   繁体   中英

How to get values from JSON using Alamofire and Swift 4.0?

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

}

/* * networking method */

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

^ When I try to get the calories for example, I get nil

In the nutritionData method I tried using .responseJSON but it was throwing an error so I switched to .responseString. I want to get the "totalNutrients" information from that JSON. Help would be appreciated

It's better to use method with responseJSON instead of 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"])
      }


  }

and then try

Ary alamofire.response, and then directly parse data in to 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)
} 

You should definitely be using responseJSON() if you just wanna serialize JSON. If you're trying to use it with a Decodable object, you should be using responseData() and decoding one of your custom types with the data. Always validate.

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

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM