You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中SignUpRequest结构体自定义编码:布尔值转custom_attributes数组

Swift自定义编码SignUpRequest为指定JSON格式

要实现将SignUpRequest结构体编码成目标JSON格式,核心是给Customer结构体实现自定义的Encodable逻辑,把privacy和privacy2布尔值转换成custom_attributes数组条目。以下是完整实现方案:

步骤1:定义辅助结构体

先创建一个CustomAttribute结构体,用来描述custom_attributes中的单个条目,通过CodingKeys映射JSON字段名:

struct CustomAttribute: Encodable {
    let attributeCode: String
    let value: String
    
    enum CodingKeys: String, CodingKey {
        case attributeCode = "attribute_code"
        case value
    }
}

步骤2:实现Customer的自定义编码

修改Customer结构体,添加CodingKeys并实现encode(to:)方法,手动控制字段编码逻辑:

struct SignUpRequest: Encodable {
    struct Customer: Encodable {
        let email: String?
        let firstname: String?
        let lastname: String?
        let privacy: Bool
        let privacy2: Bool
        
        // 映射JSON字段名
        enum CodingKeys: String, CodingKey {
            case email, firstname, lastname, customAttributes = "custom_attributes"
        }
        
        func encode(to encoder: Encoder) throws {
            var container = encoder.container(keyedBy: CodingKeys.self)
            
            // 编码基础字段
            try container.encodeIfPresent(email, forKey: .email)
            try container.encodeIfPresent(firstname, forKey: .firstname)
            try container.encodeIfPresent(lastname, forKey: .lastname)
            
            // 根据布尔值生成custom_attributes数组
            var attributes = [CustomAttribute]()
            if privacy {
                attributes.append(CustomAttribute(attributeCode: "consensopubb", value: "3"))
            }
            if privacy2 {
                attributes.append(CustomAttribute(attributeCode: "consensopubb2", value: "5"))
            }
            
            // 编码属性数组(若要省略空数组,可添加`!attributes.isEmpty`判断)
            try container.encode(attributes, forKey: .customAttributes)
        }
    }
    
    let customer: Customer
    let password: String?
}

步骤3:测试编码效果

创建实例并编码验证输出:

// 创建测试请求实例
let testCustomer = SignUpRequest.Customer(
    email: "mike.m@yopmail.com",
    firstname: "Mario",
    lastname: "Rossi",
    privacy: true,
    privacy2: true
)
let testRequest = SignUpRequest(customer: testCustomer, password: "Password1!")

// 执行编码
do {
    let jsonData = try JSONEncoder().encode(testRequest)
    if let jsonString = String(data: jsonData, encoding: .utf8) {
        print(jsonString)
    }
} catch {
    print("编码失败:\(error)")
}

输出的JSON将完全匹配目标格式,当privacy或privacy2为false时,对应的条目会自动从custom_attributes中移除。

内容的提问来源于stack exchange,提问作者Giorgio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 22:36:37