Home > Software engineering >  How to create encodable request in swift,when my request is present in Json?
How to create encodable request in swift,when my request is present in Json?

Time:09-14

I want create encodable struct request for the following JSON

{"Symbols":[{"Name":"AAS1"},{"Name":"ASSD"}],"NoOfSymbols":2,"msgtype":15}

I tried to create but getting error.Type 'SymbolName' does not conform to protocol 'Encodable'.Given my tried struct.

 struct RequestData:Encodable{
  let Symbols:[SymbolName]
  let NoOfSymbols:Int
  let msgtype: Int
 }

  struct SymbolName:Encodable{
  let Name : [String:Any]
 }

CodePudding user response:

Any cannot conform to Encodable hence the error. But it seems you don´t need SymbolName at all. Try:

struct RequestData:Encodable{
    let Symbols:[[String:String]]
    let NoOfSymbols:Int
    let msgtype: Int
}

This will create the appropriate JSON (array of dictionaries):

{"Symbols":[{"Name":"AAS1"},{"Name":"ASSD"}],"NoOfSymbols":2,"msgtype":15}

CodePudding user response:

using https://app.quicktype.io/, you get:

struct RequestData: Codable {
    let symbols: [Symbol]
    let noOfSymbols, msgtype: Int

    enum CodingKeys: String, CodingKey {
        case symbols = "Symbols"
        case noOfSymbols = "NoOfSymbols"
        case msgtype
    }
}

struct Symbol: Codable {
    let name: String

    enum CodingKeys: String, CodingKey {
        case name = "Name"
    }
}

and you can decode it like this:

 let response = try JSONDecoder().decode(RequestData.self, from: data)
 print("\n---> response: \(response)")

Similarly for encoding, such as:

let testData = RequestData(symbols: [Symbol(name: "AAS1"),Symbol(name: "ASSD")], noOfSymbols: 2, msgtype: 15)
let encodedData = try JSONEncoder().encode(testData)
print(String(data: encodedData, encoding: .utf8) as AnyObject)
  • Related