歡迎加入QQ討論群258996829

Swift JSON 解析類 Unbox

發(fā)布時間:2017-05-19 11:09  回復:0  查看:6145  感興趣:29  贊:4   最后回復:2017-05-19 11:09  
簡單易用的Swift JSON 解析類 Unbox。
示例代碼:
//JSON數據
{
    "name": "John",
    "age": 27
}

//結構體User
struct User {
    let name: String
    let age: Int
}

//User擴展Unboxable 
extension User: Unboxable {
    init(unboxer: Unboxer) throws {
        self.name = try unboxer.unbox(key: "name")
        self.age = try unboxer.unbox(key: "age")
    }
}


//解析
let user: User = try unbox(dictionary: dictionary)
//或
let user: User = try unbox(data: data)
指定KeyPath:
//JSON格式
{
    "name": "John",
    "age": 27,
    "activities": {
        "running": {
            "distance": 300
        }
    },
    "devices": [
        "Macbook Pro",
        "iPhone",
        "iPad"
    ]
}

struct User {
    let name: String
    let age: Int
    let runningDistance: Int
    let primaryDeviceName: String
}

extension User: Unboxable {
    init(unboxer: Unboxer) throws {
        self.name = try unboxer.unbox(key: "name")
        self.age = try unboxer.unbox(key: "age")
        //下面兩行指定keyPath
        self.runningDistance = try unboxer.unbox(keyPath: "activities.running.distance")
        self.primaryDeviceName = try unboxer.unbox(keyPath: "devices.0")
    }
}

相關開源代碼

您還未登錄,請先登錄

熱門帖子

最新帖子

?