当json中的字段没有值时如何发送nil?

时间:2018-12-25 06:47:35

标签: json swift

电子邮件和a_code是可选的。我确实想在空的时候发送nil。 我应该检查一下它们是否为nil,将它们从json中删除吗?

这是我要发送的json的正文

 func updateProfile(fullName: String,address: String,homePhone: String,email: String, a_code: String, completion : @escaping CompletionHandler) {
        let body : [String : Any] = [
            "name": fullName,
            "address": address,
            "h_phone": homePhone,
            "email": email,
            "a_code": a_code
        ]

        Alamofire.request(UPDATE_PROFILE_FIRST, method: .post, parameters: body, encoding: JSONEncoding.default, headers: AUTH_HEADER).validate().responseJSON { (response) in
            switch response.result {
            case .success(let value):
                let json = JSON(value)
                print(json)
                let s = json["s"].intValue
                if s == 24 {
                    completion(true)
                }else {
                    completion(false)
                }

            case .failure(let error):
                print(error.localizedDescription)
                completion(false)
            }
        }
    }

1 个答案:

答案 0 :(得分:3)

    func updateProfile(fullName: String,address: String,homePhone: String,email: String, a_code: String, completion : @escaping CompletionHandler) {
            let body : [String : Any] = [
                "name": fullName,
                "address": address,
                "h_phone": homePhone,
                "email": email.isEmpty ? nil : email ,
                "a_code": a_code.isEmpty ? nil : a_code
            ]
            ...
        }