You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从POST请求返回的JSON数据中获取指定键的值?

解决Swift解码OpenAI Chat API响应的问题

首先得定义和API返回结构完全匹配的Decodable模型,这是解码成功的核心。根据你给出的JSON格式,对应的Swift模型写法如下:

struct ChatCompletionResponse: Decodable {
    let id: String
    let object: String
    let created: Int
    let choices: [Choice]
    let usage: Usage
}

struct Choice: Decodable {
    let index: Int
    let message: Message
    let finishReason: String
}

struct Message: Decodable {
    let role: String
    let content: String
}

struct Usage: Decodable {
    let promptTokens: Int
    let completionTokens: Int
    let totalTokens: Int
}

然后修改URLSession的回调逻辑,用JSONDecoder完成解码并提取所需字段:

let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
    if let error = error {
        print("请求错误:\(error.localizedDescription)")
        return
    }
    
    guard let data = data else {
        print("未获取到返回数据")
        return
    }
    
    do {
        let decoder = JSONDecoder()
        // 自动将JSON蛇形键转为Swift驼峰命名,无需手动写CodingKeys映射
        decoder.keyDecodingStrategy = .convertFromSnakeCase
        let response = try decoder.decode(ChatCompletionResponse.self, from: data)
        
        // 提取AI回复内容
        if let aiReply = response.choices.first?.message.content {
            print("AI回复:\(aiReply)")
        }
        
        // 也可提取其他字段,比如总消耗Token数
        print("总Token消耗:\(response.usage.totalTokens)")
    } catch {
        print("解码失败:\(error.localizedDescription)")
        // 打印完整错误信息,方便排查字段不匹配等问题
        print("错误详情:\(error)")
    }
}
task.resume()

关键提示

  • 解码失败的常见原因:模型字段类型和JSON不匹配、字段名未对应、JSON存在可选字段但模型定义为必选。打印完整错误信息能快速定位问题。
  • 启用convertFromSnakeCase后,无需为每个模型手动编写CodingKeys,自动完成蛇形键到驼峰命名的映射。

内容的提问来源于stack exchange,提问作者bits

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 07:05:24