CREATE JSON SWIFTYJSON

问题描述 投票:0回答:1

我想创建一个这样的json文件

[
 {"key": "value"},
 {"key": "value"},
 {"key": "value"}
]

这是我的代码

var array: JSON = []
    for i in (0..<obj.count){
        array = [
            "user": obj[i].name!,
            "apikey": obj[i].key!
        ]
    }

但当我尝试打印时,我只得到了第一项,我如何解决这个问题?

swift xcode swift4 swifty-json
1个回答
2
投票

使用 Codable. 自从Swift 4 SwiftyJSON 落伍

struct Object : Encodable {
    private enum CodingKeys : String, CodingKey { case name  = "user", key = "apikey" }
    let name, key : String
}

let obj = [Object(name: "Foo", key: "API123"), Object(name: "Bar", key: "API456")]

do {
    let jsonData = try JSONEncoder().encode(obj)
    let jsonString = String(data: jsonData, encoding: .utf8)!
    print(jsonString)
} catch { print(error) }
© www.soinside.com 2019 - 2024. All rights reserved.