Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codable Swift 4

I am not sure how decode emotion field by using codable, it is complicated for me due structure of this JSON ... I need only parse emotion field.

{
    "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"
        }
    ]
}
like image 702
Paweł Łoziński Avatar asked Jan 28 '26 00:01

Paweł Łoziński


1 Answers

Using Codable is really awesome to decode simply json data.

Here is the basic object struct you can code to get the values (assuming the variable data is Data type you got from the 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)
}

I also suggest to read the following apple documentation for further information about Codable.

like image 124
Mindhavok Avatar answered Jan 30 '26 18:01

Mindhavok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!