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

Swift中解析JSON的结构体如何固定name字段值?

解决Swift中Codable结构体固定字段值的问题

方案一:使用只读计算属性(推荐)

这是最简洁的实现方式,将name设为只读计算属性,完全脱离JSON编码/解码逻辑的影响,无论结构体是手动初始化还是从JSON解析,name始终保持固定值:

struct QuestionConfiguration: Codable, DisplayOrderable {
    // 只读计算属性,永远返回固定字符串
    var name: String { "QuestionConfiguration" }
    
    var isRequired: Bool
    var displayOrder: Int
    var title: String = ""
    var questions: [Question]
}

计算属性不会被Codable自动合成的编码/解码逻辑处理,因此JSON中的任何内容都无法修改它的值,每次访问name都会返回你指定的固定内容。

方案二:自定义Codable实现(需参与编码/解码时用)

如果业务要求name必须被写入JSON,或必须作为存储属性存在,可以自定义Codable的编码解码逻辑,强制name值固定:

struct QuestionConfiguration: Codable, DisplayOrderable {
    var name: String = "QuestionConfiguration"
    
    var isRequired: Bool
    var displayOrder: Int
    var title: String = ""
    var questions: [Question]
    
    enum CodingKeys: String, CodingKey {
        case isRequired, displayOrder, title, questions
    }
    
    // 自定义解码逻辑,忽略JSON中的name值,强制设置固定内容
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        isRequired = try container.decode(Bool.self, forKey: .isRequired)
        displayOrder = try container.decode(Int.self, forKey: .displayOrder)
        title = try container.decodeIfPresent(String.self, forKey: .title) ?? ""
        questions = try container.decode([Question].self, forKey: .questions)
        name = "QuestionConfiguration"
    }
    
    // 自定义编码逻辑,可选:将固定的name字段写入JSON
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(isRequired, forKey: .isRequired)
        try container.encode(displayOrder, forKey: .displayOrder)
        try container.encode(title, forKey: .title)
        try container.encode(questions, forKey: .questions)
        // 手动写入固定的name字段
        try container.encode(name, forKey: .init(stringValue: "name")!)
    }
}

原问题原因分析

你之前的代码中,name是可选类型且设置了默认值,但当JSON数据中包含"name": null时,自动合成的解码逻辑会将name设为nil,覆盖默认值;只有当JSON中完全没有name字段时,默认值才会生效。而上述两种方案可以彻底避免JSON对name值的干扰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 04:20:16