在 swift 中获取对象数组的 json

get json of an array of object in swift

我想获取 swift

中对象数组的 json
class action {
    var ts: Int;
    var winner: Int;
    var meta: [Int: String];

    init(ts : Int, winner: Int, meta: [Int: String]) {
        self.ts = ts;
        self.winner = winner;
        self.meta = meta;
    }
}

var actions:[action] = []

let thisAction = action(ts: 123, winner: 1, meta: [:]);
actions.append(thisAction);

let jsonEncoder = JSONEncoder();
let jsonData = try jsonEncoder.encode(actions);

但是我有以下错误:

Fatal error: Array<action> does not conform to Encodable because action does not conform to Encodable.: file /BuildRoot/Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-900.0.74.1/src/swift/stdlib/public/core/Codable.swift, line 3962

错误信息很清楚,您需要在 Action class.

上继承 Codable
class Action: Codable {
    var ts: Int
    var winner: Int
    var meta: [Int: String]

    init(ts : Int, winner: Int, meta: [Int: String]) {
        self.ts = ts
        self.winner = winner
        self.meta = meta
    }
}

提示 1:在您的 Action class

上使用大写字母 A

提示 2:不要使用 ;,在 Swift

中不需要

提示 3:使用 do-try-catch:

do {
    let jsonData = try JSONEncoder().encode(actions)
    print(jsonData)
} catch let error {
    print(error)
}