0

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)

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Note: .prettyPrinted shouldn't be useful. This adds unnecessary info that is useful only for the human brain.
Yeah, you're right it's just a pretty visual formatting.
You're welcome. As you move forward in ios development you should check-out JSONEncoder API as well which is safer and Swifty.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.