maor yadin
maor yadin

Reputation: 61

Pass array in HTTP request body

I want to pass array like this in my request:

{
"ids": ["5ed7603ab05efe0004286d19", "5ed7608ab05efe0004286d1a"]
}

I did like that but I am not sure the server is getting as I intended:

    request.httpBody = try JSONSerialization.data(withJSONObject: ids, options: .prettyPrinted)

Upvotes: 0

Views: 1734

Answers (2)

Frankenstein
Frankenstein

Reputation: 16341

You should be using a Dictionary for this purpose. Here's how:

let dictionary = ["ids": ["5ed7603ab05efe0004286d19", "5ed7608ab05efe0004286d1a"]]
request.httpBody = try JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted)

Suggestion: The modern approach would be to use JSONEncoder(). You could google this, there are plenty of solutions online. If you're still struggling you can ask for the method in the comments, I'll help you figure out.

Update: How you can implement Swift's JSONEncoder API in your code.

let dictionary = ["ids": ["5ed7603ab05efe0004286d19", "5ed7608ab05efe0004286d1a"]]
request.httpBody = try JSONEncoder().encode(dictionary)

Using a struct would be much safer. Here's how:

typealias ID = String
struct MyRequestModel: Codable { var ids: [ID] }

let myRequestModel = MyRequestModel(ids: ["5ed7603ab05efe0004286d19", "5ed7608ab05efe0004286d1a"])
request.httpBody   = try JSONEncoder().encode(myRequestModel)

Note: Usage of type-alias is optional it just adds a bit of readability to your code, as is the usage of JSONDecoder.

Upvotes: 1

Omer Faruk Ozturk
Omer Faruk Ozturk

Reputation: 1852

You can encode using JSONEncoder;

let yourList = ["5ed7603ab05efe0004286d19", "5ed7608ab05efe0004286d1a"]

struct DataModel: Encodable {
    var ids: [String]
}

let data = DataModel(ids: yourList)
let encodedData = try! JSONEncoder().encode(data)

// JSON string value
let jsonString = String(data: encodedData, encoding: .utf8)

Upvotes: 0

Related Questions