gpt4 book ai didi

arrays - 在 Swift 4 中将 Json 对象转换为数组格式

转载 作者:行者123 更新时间:2023-11-30 10:29:34 25 4
gpt4 key购买 nike

我有 json

{
"message": null,
"data": {
"Commodity Department": {
"total": 2,
"completed": 1,
"completedWithDue": 0,
"completedWithOutDue": 1,
"inProgress": 1,
"inProgressWithDue": 0,
"inProgressWithOutDue": 1,
"statusCounter": null
}
}

我需要将每个部门的 json 对象转换为数组。当前每个类别值 ("total": 0, "completed": 0, "completedWithDue": 0, "completedWithOutDue": 0, "inProgress": 0, "inProgressWithDue": 0, "inProgressWithOutDue": 0, ) 将采用对象格式。我需要在数组中进行转换并根据类别加载到 Collection View 。截至目前,我正在尝试在下面的代码中解码我的 json

public struct Dashboard: Decodable {
public let data : [String:Departments]
}

public struct Departments: Decodable {
public let total, completed, completedWithDue, completedWithOutDue: Int
public let inProgress, inProgressWithDue, inProgressWithOutDue: Int
}

let dashboard = try? JSONDecoder().decode(Dashboard.self, from: response.data!)

print(dashboard!.data.keys)

最佳答案

您可以通过向结构添加计算属性来创建值数组

public struct Departments: Decodable {
public let total, completed, completedWithDue, completedWithOutDue: Int
public let inProgress, inProgressWithDue, inProgressWithOutDue: Int

var categoryValues: [Int] {get {
return [total, completed, completedWithDue, completedWithOutDue,
inProgress, inProgressWithDue, inProgressWithOutDue]
}
}
}

或者使用map动态创建数组

dashboard?.data.mapValues{[$0.total, $0.completed, $0.completedWithDue, ...]}

关于arrays - 在 Swift 4 中将 Json 对象转换为数组格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59425301/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com