0

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]
 }
koen
  • 5,383
  • 7
  • 50
  • 89
Manish Kumar
  • 997
  • 2
  • 13
  • 30

2 Answers2

3

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)
1

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}
burnsi
  • 6,194
  • 13
  • 17
  • 27
  • You can add create a class for Symbol ```let symbols: [Symbol]``` and use it. – Ronak Patel Sep 14 '22 at 11:40
  • @RonakPatel I am aware of that but, OP stated: `but I need array of dictionaries to be encoded`. And this does exactly that. I don´t know what they "need" or "not need". BTW. there allready is an answer focusing on what OP shoud do. – burnsi Sep 14 '22 at 12:06