【问题标题】:How to write nested dictionary in Swift 4 [closed]如何在 Swift 4 中编写嵌套字典 [关闭]
【发布时间】:2019-01-21 09:53:27
【问题描述】:

所以我有这个json:

"transactions": [
        {
            "balance": "15000",
            "description": "Makan di indomaret",
            "date": "09-01-2019",
            "week": "1"
        },
        {
            "balance": "25000",
            "description": "Makan di alfamart",
            "date": "08-01-2019",
            "week": "1"
        }
    ]

我想知道用字典写这个 json 结构。 这里是代码

var jsonData = [String : [[String : Any]]]() 

谢谢。

【问题讨论】:

  • 拜托,你能更清楚你想要达到的目标吗?
  • JSON 实际上是[String: [[String: Any]]],它是一个字典,它的值是一个字典数组,你错过了一个级别。另外,jsonData 中的“Int”键是从哪里来的?这还不清楚。
  • var jsonData = [String : [[String : Any]]]()
  • 阅读Codable,以便在 Swift 中轻松使用内置的 json 处理。

标签: swift dictionary


【解决方案1】:

应该是

var jsonData = [String : [String : Any]]()

因为键(“事务”)是字符串,它的值(

[{
    "balance": "15000",
    "description": "Makan di indomaret",
    "date": "09-01-2019",
    "week": "1"
},
{
    "balance": "25000",
    "description": "Makan di alfamart",
    "date": "08-01-2019",
    "week": "1"
}]

是一个字符串数组:任意

【讨论】:

    【解决方案2】:

    然后您可以创建一个循环来创建一个字典,该字典稍后将附加到 arrayDictionary

    let array = [[String:Any]]()

    for item in data {
     let dictionary = [String:Any]()
     dictionary["object1"] = item.id
     dictionary["object2"] = item.name
     dictionary["object3"] = item.address
    
     array.append(dictionary)
    } 
    

    【讨论】:

    • "then you can make...",这表明有些事情已经发生了。你能解释一下吗,也许只是缺少一个句子,因为我很难将这个答案与问题联系起来
    • 声明为常量的字典或数组将永远为空
    猜你喜欢
    • 2019-04-14
    • 1970-01-01
    • 2020-01-05
    • 1970-01-01
    • 2019-05-02
    • 1970-01-01
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    相关资源
    最近更新 更多