使用Swift Codable从JSON数组中提取数据 [英] Extracting data from JSON array with swift Codable

查看:154
本文介绍了使用Swift Codable从JSON数组中提取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的JSON响应:

I have a JSON response like this:

我目前将可解码结构设计如下:

I have currently designed my decodable struct to be as follows:

    struct PortfolioResponseModel: Decodable {
    var dataset: Dataset

    struct Dataset: Decodable {
        var data: Array<PortfolioData> //I cannot use [Any] here...

        struct PortfolioData: Decodable {
            //how to extract this data ?
        }
    }
   }

问题是,怎么办我将数据提取到数组中,该数组的值可以为Double或String。

The question is, how do I extract the data inside the array, which can have a value Double or String.

以下是在操场上进行此工作的示例字符串:

Here is the sample string to make this work on playground:

   let myJSONArray =
   """
   {
   "dataset": {
   "data": [
    [
   "2018-01-19",
   181.29
   ],
   [
   "2018-01-18",
   179.8
   ],
   [
   "2018-01-17",
   177.6
   ],
   [
   "2018-01-16",
   178.39
   ]
   ]
   }
   }
   """

提取数据:

do {
    let details2: PortfolioResponseModel = try JSONDecoder().decode(PortfolioResponseModel.self, from: myJSONArray.data(using: .utf8)!)
    //print(details2) 
    //print(details2.dataset.data[0]) //somehow get "2018-01-19"

} catch {
    print(error)
}


推荐答案


我不能在此处使用[Any]。

I cannot use [Any] here.

解码JSON时请勿使用任何因为通常您确实知道内容的类型。

Never use Any when decoding JSON because usually you do know the type of the contents.

要解码数组,您必须使用 unkeyedContainer 和解码序列中的值

To decode an array you have to use an unkeyedContainer and decode the values in series

struct PortfolioResponseModel: Decodable {
    var dataset: Dataset

    struct Dataset: Decodable {
        var data: [PortfolioData]

        struct PortfolioData: Decodable {
            let date : String
            let value : Double

            init(from decoder: Decoder) throws {
                var container = try decoder.unkeyedContainer()
                date = try container.decode(String.self)
                value = try container.decode(Double.self)
            }
        }
    }
}






您甚至可以将日期字符串解码为 Date

struct PortfolioData: Decodable {
    let date : Date
    let value : Double

    init(from decoder: Decoder) throws {
        var container = try decoder.unkeyedContainer()
        date = try container.decode(Date.self)
        value = try container.decode(Double.self)
    }
}

如果在解码器中添加日期格式化程序

if you add a date formatter to the decoder

let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(formatter)
let details2 = try decoder.decode(PortfolioResponseModel.self, from: Data(myJSONArray.utf8))

这篇关于使用Swift Codable从JSON数组中提取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆