如何将数组值添加到 JSON 输入 Swift

How to add Array value to JSON Key in Swift

如何添加request.httpBody = getPostData(params: ["contactsList": ["1212121212, "5555555544"]])代替 let parameters = getPostString(params: ["contactsList":[phNumArray]])

下面是工作代码,但如何添加 phNumArray 代替个人号码到联系人列表

API 的 Postman 输出:

工作代码:任何人都可以复制粘贴以查看输出

import UIKit
class TestViewController: UIViewController {
    var phNumArray = ["1111111111", "5555555544"]
    override func viewDidLoad() {
        super.viewDidLoad()

        callPostApi()
    }

    func getPostString(params: [String: Any]) -> String {
        var data = [String]()
        for (key, value) in params {
            data.append(key + "=\(value)")
        }
        print(data.map { String([=12=]) }.joined(separator: "&"))
        return data.map { String([=12=]) }.joined(separator: "&")
    }

    func callPostApi() {
        let url = URL(string: "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/filter/taggedusers/")
        guard let requestUrl = url else { fatalError() }
        var request = URLRequest(url: requestUrl)
        request.httpMethod = "POST"

        request.setValue("EC3746E9-4DB4-42C7-9D8C-1542B18C2AC", forHTTPHeaderField: "deviceid")
        request.setValue("5fe42fb3b54543a0bab5667cf96526f8", forHTTPHeaderField: "key")
        request.setValue("personal", forHTTPHeaderField: "userType")

        let parameters = getPostString(params: ["contactsList": ["5555555544", "11111111111"]])

        print("json parameter phone numbers \(parameters)")

        request.httpBody = parameters.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            let httpResponse = response as? HTTPURLResponse
            // Check for Error
            if let error = error {
                print("Error took place \(error)")
                return
            }
            if let data = data, let dataString = String(data: data, encoding: .utf8) {
                print("Response data string:\n \(dataString)")

                do {
                    let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: Any]
                    print("fetching json \(json)")
                    let fetchStatus = json["userName"] as? String
                    print("fetching json userName \(String(describing: fetchStatus))")

                    let user = json["5555555544"] as? [String: Any]
                    let name = user?["userName"] as? String
                    print("first username \(name)")
                } catch {}
            }
        }
        task.resume()
    }
}

请帮我解决 contactsList 值的问题。

更新:这次您发送的请求一直是 JSON 编码,而不是 form-data。我在下面添加了代码,试试看:

class ViewController: UIViewController {

    var phNumArray  = ["1111111111", "5555555544"]

    override func viewDidLoad() {
        super.viewDidLoad()

        callPostApi()
    }

    func getPostData(params: [String:Any]) -> Data? {
        return try? JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
    }

    func callPostApi() {

        let url            = URL(string: "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/filter/taggedusers/")!
        var request        = URLRequest(url: url)
        request.httpMethod = "POST"

        request.setValue("EC3746E9-4DB4-42C7-9D8C-1542B18C2AC", forHTTPHeaderField: "deviceid")
        request.setValue("5fe42fb3b54543a0bab5667cf96526f8", forHTTPHeaderField: "key")
        request.setValue("personal", forHTTPHeaderField: "userType")

        try? request.setMultipartFormData(["contactsList": "\(phNumArray)"], encoding: .utf8)

        URLSession.shared.dataTask(with: request) { data, _, _ in
            if let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {

                let user = json["5555555544"] as? [String: Any]
                let name = user?["userName"] as? String
                print("first username \(name)")
            }
        }.resume()
    }
}

extension URLRequest {

    public mutating func setMultipartFormData(_ parameters: [String: String], encoding: String.Encoding) throws {

        let makeRandom = { UInt32.random(in: (.min)...(.max)) }
        let boundary = String(format: "------------------------%08X%08X", makeRandom(), makeRandom())

        let contentType: String = try {
            guard let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(encoding.rawValue)) else {
                throw MultipartFormDataEncodingError.characterSetName
            }
            return "multipart/form-data; charset=\(charset); boundary=\(boundary)"
        }()
        addValue(contentType, forHTTPHeaderField: "Content-Type")

        httpBody = try {
            var body = Data()

            for (rawName, rawValue) in parameters {
                if !body.isEmpty {
                    body.append("\r\n".data(using: .utf8)!)
                }

                body.append("--\(boundary)\r\n".data(using: .utf8)!)

                guard
                    rawName.canBeConverted(to: encoding),
                    let disposition = "Content-Disposition: form-data; name=\"\(rawName)\"\r\n".data(using: encoding) else {
                    throw MultipartFormDataEncodingError.name(rawName)
                }
                body.append(disposition)

                body.append("\r\n".data(using: .utf8)!)

                guard let value = rawValue.data(using: encoding) else {
                    throw MultipartFormDataEncodingError.value(rawValue, name: rawName)
                }

                body.append(value)
            }

            body.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)

            return body
        }()
    }
}

public enum MultipartFormDataEncodingError: Error {
    case characterSetName
    case name(String)
    case value(String, name: String)
}

不要先转换成JSON String再转换成Data,而是使用JSONSerialization,下面是一个例子:

func getPostData(params:[String:Any]) -> Data? {
    return try? JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
}

然后直接赋值给URLRequesthttpBody,像这样:

let arrayOfNumbers = [String]()
arrayOfNumbers.append("5555555544")
arrayOfNumbers.append("11111111111")
request.httpBody = getPostData(params: ["contactsList": arrayOfNumbers])

此外,浏览 Apple Documentation,您会在那里找到有价值的信息。如果不理解那里的概念 google 更多关于 JSON 序列化和 POST 请求 httpBody。