gpt4 book ai didi

ios - 可编码 swift 4

转载 作者:可可西里 更新时间:2023-11-01 00:39:10 24 4
gpt4 key购买 nike

我不确定如何使用 codable 解码情感字段,由于此 JSON 的结构,这对我来说很复杂......我只需要解析情感字段。

{
"image_id": "HvRRq86gYY96sVNP+lXHYg==",
"request_id": "1525001300,f1cf060a-dbba-424a-ad75-c315298bbadb",
"time_used": 444,
"faces": [
{
"attributes": {
"emotion": {
"sadness": 13.562,
"neutral": 86.409,
"disgust": 0.001,
"anger": 0.003,
"surprise": 0.002,
"fear": 0.022,
"happiness": 0.001
}
},
"face_rectangle": {
"width": 800,
"top": 451,
"left": 58,
"height": 800
},
"face_token": "75985eed763e1a7cc9aad61c88f492a1"
}
]
}

最佳答案

使用 Codable 来解码简单的 json 数据真的很棒。

这是您可以编写代码以获取值的基本对象结构(假设变量数据是您从 json 中获取的数据类型):

struct FaceRectangle: Codable {
var width: Int
var top: Int
var left: Int
var height: Int
}

struct Emotion: Codable {
var sadness: Float
var neutral: Float
var disgust: Float
var anger: Float
var surprise: Float
var fear: Float
var happiness: Float
}

struct Attribute: Codable {
var emotion: Emotion
}

struct Faces: Codable {
var attributes: Attribute
var face_rectangle: FaceRectangle
var face_token: String
}

struct Result : Codable {
var image_id: String
var request_id: String
var time_used: Int
var faces: [Faces]
}

do {
let obj: Result = try JSONDecoder().decode(Result.self, from: data)
print(obj.faces[0].attributes.emotion.anger)
} catch let err {
print(err)
}

我还建议阅读以下内容 apple documentation有关 Codable 的更多信息。

关于ios - 可编码 swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50086418/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com