【问题标题】:Parsing Dynamic Json in Swift在 Swift 中解析动态 Json
【发布时间】:2020-04-17 01:54:19
【问题描述】:
{
  "AAPL" : {
    "quote": {...},
    "news": [...],
    "chart": [...]
  },
  "FB" : {
    "quote": {...},
    "news": [...],
    "chart": [...]
  },
}

您将如何快速解码。股票会发生变化,但基础报价、新闻和图表保持不变。还要提到这个 json 的股票可能有 500 长,排序顺序未知。

对于报价中的信息,它看起来像:

{

"calculationPrice": "tops",
"open": 154,
ect...

}

内幕消息:

[
  {
    "datetime": 1545215400000,
    "headline": "Voice Search Technology Creates A New Paradigm For 
     Marketers",
     ect...
  }
]

内部图表:

[
    {
        "date": "2017-04-03",
        "open": 143.1192,
        ect...
    } 
]

我一直在尝试的是类似这样的例子......

Json 响应:

{
  "kolsh" : {
    "description" : "First only brewed in Köln, Germany, now many American brewpubs..."
  },
  "stout" : {
    "description" : "As mysterious as they look, stouts are typically dark brown to pitch black in color..."
  }
}

可编码的结构/模型:

struct BeerStyles : Codable {
  struct BeerStyleKey : CodingKey {
    var stringValue: String
    init?(stringValue: String) {
      self.stringValue = stringValue
    }
    var intValue: Int? { return nil }
    init?(intValue: Int) { return nil }

    static let description = BeerStyleKey(stringValue: "description")!
  }

  struct BeerStyle : Codable {
    let name: String
    let description: String
  }

  let beerStyles : [BeerStyle]
}

解码器:

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

    var styles: [BeerStyle] = []
    for key in container.allKeys {
        let nested = try container.nestedContainer(keyedBy: BeerStyleKey.self,
            forKey: key)
        let description = try nested.decode(String.self,
            forKey: .description)
        styles.append(BeerStyle(name: key.stringValue,
            description: description))
    }

    self.beerStyles = styles
}

这个例子来自https://benscheirman.com/2017/06/swift-json/,我正在尝试将它应用到我的 json 结构中。

【问题讨论】:

  • 一个好的堆栈溢出问题不仅需要您想要完成的内容,还需要您已经尝试过的内容。欲了解更多信息,请参阅How to ask a good question?
  • 类似于 json?["AAPL"]["quote"] 的东西。和 json?["AAPL"][1]["chart"]
  • 报价、新闻和图表的内容是什么?

标签: json swift dynamic


【解决方案1】:

试试这个代码...:)

    Alamofire.request("", method: .get, encoding: JSONEncoding.default) .responseJSON { response in
            if response.result.isSuccess{
                let json = response.result.value! as? [String : Any] ?? [:]

                for (key, value) in json {

                //here key will be your apple , fb

                let valueofkey = value as? [String:Any] ?? [:]
                let quote = valueofkey["quote"] as? [String:Any] ?? [:]
                let news = valueofkey["news"] as? [Any] ?? []
                let chart = valueofkey["chart"] as? [Any] ?? []


            }

            }
        }

我希望它对你有用...... :)

【讨论】:

  • 谢谢,稍作修改后确实可以使用。
【解决方案2】:

如果quotenewschart的内容类型相同,即假设quote的类型为[String:String]news,图表的类型为[String],则可以使用Codable 也是。

例子:

使用以下模型,

struct Model: Decodable {
    let quote: [String:String]
    let news: [String]
    let chart: [ String]
}

现在,您可以像这样解析 JSON,

do {
    let response = try JSONDecoder().decode([String:Model].self, from: data)
    print(response)
} catch {
    print(error)
}

【讨论】:

    猜你喜欢
    • 2021-05-18
    • 2020-11-06
    • 1970-01-01
    • 2020-07-28
    • 2015-01-21
    • 1970-01-01
    • 1970-01-01
    • 2019-12-27
    相关资源
    最近更新 更多