Codable with noisy JSON 响应

Codable with noisy JSON response

一般来说,我了解 Codable 的工作原理。一个简单的例子是:

[
    {
        "id": 1,
        "name": "Paul",
        "photo": {
            "id": 48,
            "url": "https://..."
        }
    },
    {
        "id": 2,
        "name": "Andrew",
        "photo": {
            "id": 389,
            "url": "https://..."
        }
    }
]

这需要两个简单的结构:

struct User: Codable {
    var id: Int
    var name: String
    var photo: Photo
}

struct Photo: Codable {
    var id: Int
    var url: String
}

鉴于上面的例子,我的 API 的回复 json 的格式更复杂:

{
    "data": [
        {
            "data": {
                "id": 1,
                "attributes": {
                    "name": "Paul"
                },
                "relationships": {
                    "photo": {
                        "data": {
                            "id": 48,
                            "attributes": {
                                "url": "https://..."
                            }
                        }
                    }
                }
            }
        },
        {
            "data": {
                "id": 2,
                "attributes": {
                    "name": "Andrew"
                },
                "relationships": {
                    "photo": {
                        "data": {
                            "id": 389,
                            "attributes": {
                                "url": "https://..."
                            }
                        }
                    }
                }
            }
        }
    ]
}

我已经尝试使用 SwiftyJSON 来预解析/展平 json,方法是消除所有噪音并尝试制作类似于第一个 json 示例中的格式。但是,我觉得可能有更好、更明显的方法来做到这一点,并且操纵 json 似乎很容易出错。

我读过有关 CodingKeys 的内容,但在这一点上,这几乎与使用 SwiftyJSON 手动解析 json 一样多。

有谁知道如何高效做到这一点?

使用 quicktype.io 从指定的 JSON 为您生成响应模型。

import Foundation

// MARK: - Root
struct Root: Codable {
    let data: [Datum]
}

// MARK: - Datum
struct Datum: Codable {
    let data: DatumData
}

// MARK: - DatumData
struct DatumData: Codable {
    let id: Int
    let attributes: PurpleAttributes
    let relationships: Relationships
}

// MARK: - PurpleAttributes
struct PurpleAttributes: Codable {
    let name: String
}

// MARK: - Relationships
struct Relationships: Codable {
    let photo: Photo
}

// MARK: - Photo
struct Photo: Codable {
    let data: PhotoData
}

// MARK: - PhotoData
struct PhotoData: Codable {
    let id: Int
    let attributes: FluffyAttributes
}

// MARK: - FluffyAttributes
struct FluffyAttributes: Codable {
    let url: String
}

let root = try JSONDecoder().decode(Root.self, from: jsonData)