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

在iOS中使用Swift 4将多层JSON解码为结构体

没问题,我来帮你搞定这个JSON到Swift结构体的解码逻辑~ 这里的核心是要从localizedValues字典里,根据fallbackLanguage的值提取对应的description,毕竟你的结构体X里并没有直接对应localizedValues的属性,而是需要把这个字典转成单个的description字段。

实现自定义JSON解码逻辑

我们可以借助Swift的Codable协议来实现这个自定义解码场景,下面是完整的可运行代码:

import Foundation

struct X: Codable {
    let name: String
    let owner: String
    let fallbackLanguage: String
    let description: String
    
    // 自定义解码初始化器,处理字段映射逻辑
    init(from decoder: Decoder) throws {
        // 获取JSON键值对容器
        let container = try decoder.container(keyedBy: CodingKeys.self)
        
        // 先解码基础的字符串字段
        name = try container.decode(String.self, forKey: .name)
        owner = try container.decode(String.self, forKey: .owner)
        fallbackLanguage = try container.decode(String.self, forKey: .fallbackLanguage)
        
        // 定义辅助结构体,用来解析localizedValues里的单个语言对象
        private struct LocalizedDescription: Codable {
            let description: String
        }
        
        // 解码localizedValues字典:键是语言代码,值是带description的对象
        let localizedValues = try container.decode([String: LocalizedDescription].self, forKey: .localizedValues)
        
        // 根据fallbackLanguage查找对应的描述,找不到则抛出解码错误
        guard let targetDesc = localizedValues[fallbackLanguage] else {
            throw DecodingError.dataCorruptedError(
                forKey: .localizedValues,
                in: container,
                debugDescription: "找不到fallback语言\(fallbackLanguage)对应的描述内容"
            )
        }
        description = targetDesc.description
    }
    
    // 定义编码键,关联Swift属性和JSON字段名
    enum CodingKeys: String, CodingKey {
        case name, owner, fallbackLanguage, localizedValues
    }
}

// 测试解码功能
let testJson = """
{ 
    "name": "abc", 
    "owner": "bcd", 
    "fallbackLanguage": "tr", 
    "localizedValues": { 
        "en": { "description": "Lorem Ipsum Dolor Sit Amet" }, 
        "de": { "description": "Sed Do Eiusmod Tempor Incididunt" }, 
        "tr": { "description": "Consectetur Adipisicing Elit" } 
    } 
}
"""

if let jsonData = testJson.data(using: .utf8) {
    do {
        let decodedModel = try JSONDecoder().decode(X.self, from: jsonData)
        print(decodedModel.description) // 会输出 "Consectetur Adipisicing Elit"
    } catch {
        print("解码失败:\(error.localizedDescription)")
    }
}

代码说明

  • 辅助结构体LocalizedDescription:用来解析localizedValues字典里的单个语言对象,简化字典值的解码操作。
  • 自定义init(from:):这是核心逻辑所在,我们先解码基础字段,再解析localizedValues字典,最后根据fallbackLanguage提取目标描述。如果找不到对应语言的描述,会抛出明确的错误信息,方便调试。
  • 容错调整:如果你不想在找不到语言时抛出错误,可以把guard语句改成容错逻辑,比如:
    description = localizedValues[fallbackLanguage]?.description ?? "默认描述内容"
    

内容的提问来源于stack exchange,提问作者Arda Oğul Üçpınar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:30:31