Search code examples
arraysjsonswiftstructjsonserializer

Serialize heterogenic array


I have a following JSON string, which I need to serialize and send as a body in POST request.

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

I'm having problems converting it into a Swift object. As you can see, the rules property contains heterogenic array with either [Rule] or Rule objects, which have following structure:

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
    }
}

What to do to convert the above JSON into Data?


Solution

  • If you have the below JSON String,

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

    Simply use data(using:) to convert String to Data like,

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