Swift:解析一个您不知道键值的JSON文件

我正在构建一个使用json查询wikidata的应用程序。到目前为止,它仍然有效,但是我遇到的问题是我从wikidata获得的响应不是实际数据,而是标识符。然后,要转换该标识符,我需要将其发送到另一个url并接收另一个json响应,但是直到遇到第一个json响应,我才知道关键问题是关键值。 ,假设我的密钥是Q1169621。当我通过api运行它时,得到以下响应:

Swift:解析一个您不知道键值的JSON文件

我正在使用codable和JSONDecoder,但是我不知道如何告诉解码器实体中的键的值是Q1169621以达到我想要的值(“ Jim Lauderdale”)...我的一些在下面的代码中,我具有用于定义响应数据的结构,但是如何将结构中的键值替换为从先前解码的json定义的键值?

struct InfoFromWikiConverted: Codable {
    
    let entities: Locator //this is the value I need to set before parsing the json
    
}

struct Locator: Codable {
    
    let labels: Labels //how do I link this to the struct above?
}

struct Labels: Codable {
    
    let en: EN
}

struct EN: Codable {
    
    let value: String
}
iCMS 回答:Swift:解析一个您不知道键值的JSON文件

最简单的方法是将entities解码为[String: Locator]

struct InfoFromWikiConverted: Decodable {
   let entities: [String: Locator]
}

当然,如果您希望模型只是一个Locator(这意味着可能忽略entities下的多个键),则需要手动对其进行解码。

您需要创建一种类型来表示任何字符串Coding Key并实现init(from:)

struct InfoFromWikiConverted: Decodable {
   let entities: Locator
   
   struct CodingKeys: CodingKey {
      var stringValue: String
      var intValue: Int? = nil
        
      init(stringValue: String) { self.stringValue = stringValue }
      init?(intValue: Int) { return nil }
   }

   init(from decoder: Decoder) throws {
      let container = try decoder.container(keyedBy: CodingKeys.self)

      // get the first key (ignore the rest),and throw if there are none
      guard let key = container.allKeys.first else {
         throw DecodingError.dataCorrupted(
            .init(codingPath: container.codingPath,debugDescription: "Expected a non-empty object"))
      }

      let entities = try container.decode(Locator.self,forKey: key)
   }
}

请注意,由于您没有保留ID,因此无法将其编码回相同的格式,因此我仅遵循Decodable而不是Codable

本文链接:https://www.f2er.com/1779734.html

大家都在问