【问题标题】:Decoding JSON APIs in Swift - Duplicate Struct Names在 Swift 中解码 JSON API - 重复的结构名称
【发布时间】:2021-06-11 15:46:12
【问题描述】:

我的应用在 Swift 中解析了许多 API,其中一些 API 具有相似的字典和/或数组名称。

我无法控制传入的 JSON 字典数组的名称,因为它们来自 API 端点。目前我有一个处理所有这些 API 的实用程序类。如何解析共享通用名称的 API?

这是我用于一个 API 的内容。

 struct aVideo: Codable {
        let page, totalResults, totalPages: Int
        let results: [Result]
        
        enum CodingKeys: String, CodingKey {
            case page
            case results
        }
    }
    
    // MARK: - Result
    struct Result: Codable {
        let popularity: Double
        let voteCount: Int
        let video: Bool
    }

此其他 API 使用相同的键 Result 并引发错误。

// MARK: - WordInfo
    struct WordInfo: Codable {
        let word: String
        let results: [Result]
        let frequency: Double
    }

     // MARK: - Result
    struct Result: Codable {
        let definition, partOfSpeech: String
        let synonyms, entails, hasTypes, derivation: [String]
    }

感谢您的任何建议。

【问题讨论】:

    标签: ios json swift struct


    【解决方案1】:

    JSON 本身并没有定义结构的名称——只定义了包含它的属性的名称,因此您可以根据需要重新定义结构的名称:

    struct WordInfo: Codable {
            let word: String
            let results: [WordInfoResult]
            let frequency: Double
        }
    
         // MARK: - Result
        struct WordInfoResult: Codable {
            let definition, partOfSpeech: String
            let synonyms, entails, hasTypes, derivation: [String]
        }
    

    解码器会知道,当它到达WordInfo 上的results 时,它应该被解析为[WordInfoResult] 类型,因为这就是你定义它的方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多