序列化异构数组

Serialize heterogenic array

我有一个 JSON 字符串,我需要将其序列化并作为正文发送到 POST 请求中。

{
    "rules": [[
        {
            "operator": "text_field_contains",
            "args": [
                "8",
                "test"
            ]
        }],
        [{
            "operator": "text_field_contains",
            "args": [
                "6",
                "test"
            ]
        }
    ],
    {
        "operator": "status_any",
        "args": []
    }
    ]
}

我在将其转换为 Swift 对象时遇到问题。如您所见,rules 属性 包含具有 [Rule]Rule 对象的异构数组,其结构如下:

struct Rule: Codable, Equatable {
    let rOperator: String
    let args: [String]?

    enum CodingKeys : String, CodingKey {
        case rOperator = "operator"
        case args
    }

    init(ruleOperator: String, args: [String]? = nil) {
        self.rOperator = ruleOperator
        self.args = args
    }
}

如何将上面的JSON转换成数据?

如果你有以下 JSON String,

    let str = """
    {"rules":[[{"operator":"text_field_contains","args":["8","test"]}],[{"operator":"text_field_contains","args":["6","test"]}],{"operator":"status_any","args":[]}]}
    """

只需使用data(using:)String转换为Data

    if let data = str.data(using: .utf8) {
        //use data here....
    }