Home > Enterprise >  How to create a JSON in SWFT using users input data?
How to create a JSON in SWFT using users input data?

Time:09-17

I need to create a JSON like this:

{
    "var1": "1",
    "var2": "2",
    "newArray": [{
        "Deleted": false
    }]
}

My Codable looks like this:

struct RequestModel: Codable {
    var var1: String?
    var var1: String?
    var Treatments: [Treat]
    
}


struct Treat: Codable {
    var adminBy: String?
}

So, now I need to create the above JSON... I tried the following:

let adminBy = adminByTextField.text ?? ""
let VAR1 = var1TextField.text ?? ""
let VAR2 = var2TextField.text ?? ""

let dict  = ["adminBy":adminBy] as! NSDictionary


///And I TRY to create my JSON here


private func createRequestObject() -> RequestModel {

    let request = RequestModel(var1: VAR1,
                               var2: VAR2,
                               Treatments: dict)

    return request
}

But I get this error:

enter image description here

I don't understand why this error occurs or how to fix it.

any advice would be appreciated.

CodePudding user response:

You should not be using an NSDictionary here. You RequestModel object requires an array of Treat.

You could create the array in the following way and pass it to your RequestModel :

let adminBy = adminByTextField.text ?? ""
let VAR1 = var1TextField.text ?? ""
let VAR2 = var2TextField.text ?? ""

let treats = [Treat(adminBy: adminBy)]
let request = RequestModel(var1: VAR1, var2: VAR2, Treatments: treats)
  • Related