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

Swift 4 Codable解析JSON中emotion字段的技术疑问

用Swift 4 Codable解析JSON中的emotion字段

没问题,我来帮你搞定这个需求!你的JSON结构虽然层级多,但只要我们只定义需要的字段模型,就能轻松拿到emotion数据,完全不用管那些不需要的内容。

步骤1:定义对应层级的Codable模型

我们只需要把从根到emotion的必要层级用结构体对应起来,不需要的字段直接忽略(Codable会自动跳过未定义的字段):

// 最底层的emotion模型,对应你需要的所有情绪字段
struct Emotion: Codable {
    let sadness: Double
    let neutral: Double
    let disgust: Double
    let anger: Double
    let surprise: Double
    let fear: Double
    let happiness: Double
}

// 包裹emotion的attributes模型
struct FaceAttributes: Codable {
    let emotion: Emotion
}

// 包裹attributes的face模型
struct Face: Codable {
    let attributes: FaceAttributes
}

// 根模型,只需要包含faces数组
struct FaceRecognitionResult: Codable {
    let faces: [Face]
}

步骤2:执行解析操作

假设你已经拿到了JSON对应的Data对象,用JSONDecoder解析即可:

// 示例:从JSON Data解析
func parseEmotion(from jsonData: Data) {
    do {
        let result = try JSONDecoder().decode(FaceRecognitionResult.self, from: jsonData)
        
        // 处理解析结果,比如取出第一个人脸的emotion
        if let firstFaceEmotion = result.faces.first?.attributes.emotion {
            print("中性情绪占比:\(firstFaceEmotion.neutral)%")
            print("悲伤情绪占比:\(firstFaceEmotion.sadness)%")
            // 其他情绪字段可以按需调用
        } else {
            print("未检测到人脸数据")
        }
    } catch {
        print("解析失败:\(error.localizedDescription)")
    }
}

关键说明

  • Codable协议会自动为我们合成编码/解码逻辑,不需要手动写init(from decoder:)或者encode(to encoder:)方法。
  • 所有未在模型中定义的字段(比如image_id、face_rectangle等)都会被自动忽略,不会影响解析流程。
  • 如果JSON中的faces数组可能包含多个人脸,你可以遍历result.faces数组来获取每个人的emotion数据。

内容的提问来源于stack exchange,提问作者Paweł Łoziński

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:30:39