从字典中获取json数组

时间:2020-06-20 14:53:17

标签: ios swift dictionary

我有4个具有不同名称的字典,如下所示...

let dict = [
    "ResolutionID": [1: "101", 2: "102", 3: "103", 0: "100"],
    
    "Planned":   [3: "Y", 1: "Y", 2: "Y"],
    
    "Done":  [2: "Y"],
    
    "Who": [2: "qw", 0: "bcc"]
]

这些字典的名称与json对象的键名相对应,上述字典中的键(0、1,2等)与数组中的json对象总数相对应。因此,在上述情况下,由于字典中的最大键是3,所以我的json数组中将有4个对象(0-3)

所以我想创建一个最终看起来像这样的json数组...

[
  {
    "ResolutionID":100,
    "Who":"bcc",
    "Planned":"",
    "Done":""
  },
  {
    "ResolutionID":101,
    "Who":"",
    "Planned":"Y",
    "Done":""
  },
  {
    "ResolutionID":102,
    "Who":"qw",
    "Planned":"Y",
    "Done":"Y"
  },
  {
    "ResolutionID":103,
    "Who":"",
    "Planned":"Y",
    "Done":""
  }
]

我尝试使用mergemerging。但这没用...

现在我不确定如何获得此结果...

编辑:这是我尝试过的。

我尝试使用for循环比较相同的键,然后将它们添加到数组中。但是它分配了错误的值。这就是我尝试过的...

for (indexSel,plantCode) in selectionOptionDic {
    resolutionDict["ResolutionID"] = plantCode
    for (indexPL,planned) in selectionPlannedDic {
        if indexPL == indexSel {
            resolutionDict["Planned"] = planned
        }
        for (indexDone,done) in selectionDoneDic {
            if indexDone == indexPL {
                resolutionDict["Done"] = done
            }
            for (indexWho,text) in selectionWhoDic {
                if indexWho == indexDone {
                    resolutionDict["Who"] = text
                }
                
            }
        }
        arrayOfResolutions.append(resolutionDict)
    }
}

1 个答案:

答案 0 :(得分:0)

如果您的最终目标是一个json数组,我认为最好使用实现Codable

的结构
struct Resolution: Codable {
    let resolutionId: String
    let planned: String
    let done: String
    let who: String

    init(id: String, planned: String?, done: String?, who: String?) {
        self.resolutionId = id
        self.planned = planned ?? ""
        self.done = done ?? ""
        self.who = who ?? ""
    }

    enum CodingKeys: String, CodingKey {
        case resolutionId = "ResolutionID"
        case planned = "Planned"
        case done = "Done"
        case who = "Who"
    }
}

然后执行以下转换

let arrayOfResolutions = selectionOptionDic.map { 
    Resolution(id: $0.value,
               planned: selectionPlannedDic[$0.key],
               done: selectionDoneDic[$0.key],
               who: selectionWhoDic[$0.key])
}