简体   繁体   English

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

[英]how to send nil when there is no value for a field in json?

email and a_code are optional. email和a_code是可选的。 i do want to send nil when they are empty. 我确实想在空的时候发送nil。 should i check and if they were nil ,remove them from json? 我应该检查它们是否为nil,将它们从json中删除吗?

this is the body for json i want to send 这是我要发送的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)
            }
        }
    }
    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
            ]
            ...
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM