Paw*_*ski 3 parsing json key ios swift
我不确定如何使用 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"
}
]
}
Run Code Online (Sandbox Code Playgroud)
使用 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)
}
Run Code Online (Sandbox Code Playgroud)
我还建议阅读以下Apple 文档以获取有关 Codable 的更多信息。
| 归档时间: |
|
| 查看次数: |
1250 次 |
| 最近记录: |