alamofire 从 api 请求访问数组中的项目

问题描述 投票:0回答:1

我有以下代码,正在使用 alamofire 进行 API 调用。

API 的响应如下所示:

{
  "translations": [
    {
      "detected_source_language": "EN",
      "text": "Hallo, Welt!"
    }
  ]
}

我的问题是如何在成功块中访问

"text": "Hallo, Welt!"

我目前的代码看起来像这样。

我在成功块中尝试了很多东西,下面是最新的尝试。谁能看到我做错了什么?

struct Post: Encodable {
    let text: String
    let target_lang: String
}


let requestBody = Post(text: translatedTextRequest, target_lang: "en")
 
AF.request(
    "http"//www.test.com"
    method: .post,
    parameters: requestBody,
    encoder: JSONParameterEncoder.default).response { response in
         switch response.result {
            case let .success(value):
                do {
                  let json = try JSONSerialization.jsonObject(with: value!, options: [])
                  if let dict = json as? [String: Any],
                  let translatedText = dict["text"] as? String {
                       print(translatedText)  <--- how can I correctly access translated text here
                  } else {
                       print("Invalid response format")
                   }
              } catch {
                  print("Error decoding response: \(error)")
           }

           case let .failure(error):
                 print(error)
           }
       }              
swift swiftui alamofire
1个回答
-1
投票

你可以试试

struct RootResponse: Encodable {
    let translations: [Post] 
}

struct Post: Encodable {
    let detected_source_language ,text: String
}
AF.request("http"//www.test.com",
               method: .post,
               parameters: requestBody,
               encoder: JSONParameterEncoder.default).responseJSON{ response in
               print(response.result) 

            switch response.result {
            case .success:
                if let data = response.data {
                    print(data)
                    // Convert This in JSON
                    do {
                        let res = try JSONDecoder().decode(RootResponse.self, from: data)
                        print(res.translations.first?.text)
                    }catch {
                        print(error)
                    }

                }
            case .failure(let error):
                print("Error:", error)
            }

}
© www.soinside.com 2019 - 2024. All rights reserved.