Home > Blockchain >  Alamofire - how to send an array of keyless objects
Alamofire - how to send an array of keyless objects

Time:09-16

I am trying to send an API request that looks like this

[
  {
    "thing": "",
  },
]

Based on an array of an object like this

struct Something {
  var thing: String? = nil
}

[Something]

AF.request(path, method: .put, parameters: params, encoding: JSONEncoding.default, headers: headers)

It has become very apparent that Alamofire is incapable of doing this and expects the objects to be a dictionary like this [String, Any]

[
  "parentThing": {
    "thing": "",
  },
]

This is not an option here. I have found a handful of possible solutions, none of which have worked in this case.

Any help would be greatly appreciated!

For an exhaustive list of things i have found and tried, https://stackoverflow.com/a/44551842/1386556 or https://stackoverflow.com/a/27027253/1386556 - these result in each of the models being converted to a string like so. Obviously an array of strings is not the intent. It really needs to be an array of JSONObjects.

["{\"thing\":\"\",}"]

CodePudding user response:

Instead of using the request(..., encoding:) version, make your parameters Encodable and use the request(..., encoder: JSONParameterEncoder()) version, which properly supports encoded arrays of values.

CodePudding user response:

Send data like this [[String: AnyObject]]

Example:

func preparaeData() -> [[String: AnyObject]] {
    var data: [[String: AnyObject]] = [[String: AnyObject]]()
    
    for (item) in yourArray {
      let dataDictionary: [String: AnyObject] = ["thing": item.thing as AnyObject]
      data.append(dataDictionary)
    }
    
    return data
  }
  • Related