在 Swift 4 中将 Json 对象转换为数组格式
Posted
技术标签:
【中文标题】在 Swift 4 中将 Json 对象转换为数组格式【英文标题】:Convert Json Object to Array format in Swift 4 【发布时间】:2019-12-20 12:30:09 【问题描述】:我有 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,)
将采用对象格式。我需要转换数组并根据类别加载到collectionview。截至目前,我正在尝试在下面的代码中解码我的 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)
【问题讨论】:
问题是什么? @vadian 当前每个类别的值(“total”:0,“completed”:0,“completedWithDue”:0,“completedWithOutDue”:0,“inProgress”:0,“inProgressWithDue”:0 , "inProgressWithOutDue": 0,) 将是对象格式。我需要根据类别将数组加载转换为collectionview 为了便于阅读,请将代码添加到您的问题中,而不是在 cmets 中。另外,print(dashboard!.data.keys)
的输出是什么?
这能回答你的问题吗? How to parse Array of JSON to array in Swift
@koen 我得到了部门名称 All Departments, Portfolio Mangement Service.....
【参考方案1】:
您可以通过向结构添加计算属性来创建值数组
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, ...]
【讨论】:
我收到一个错误缺少返回预期返回“[Int]”的函数 抱歉,这是 Swift 5 的新功能。 如何访问密钥 数组中没有键,但值的顺序始终相同。想要key就需要字典,解决方法基本一样【参考方案2】:您可以在不知道密钥的情况下解码 json,如下所示:
func printJSON(json: [String:Any])
let jsonKeys = json.keys //Gets the list of keys on the outer-most layer of the JSON
for i in 0..<jsonKeys.count
let level1 = json[jsonKeys.index(jsonKeys.startIndex, offsetBy: i)] //retrieves the object with the specific keys
if let level2 = json[level1.key] as? [String:Any] //if the key is another object
printJSON(json: level2) //send it as a new json object to the function again
else if let level2 = json[level1.key] as? [[String:Any]] //if the key is an array of objects
for i in 0..<level2.count //loop through the array
printJSON(json: level2[i]) //send each array element to the function
else if let value = json[level1.key] as? String //if value of String/Integer/Bool type
print(value) //then only print values of the specified type (String-type in this case)
查看全文Here
【讨论】:
以上是关于在 Swift 4 中将 Json 对象转换为数组格式的主要内容,如果未能解决你的问题,请参考以下文章
如何在 swift 3 中将具有自定义类的数组转换为 JSON
如何在 Swift 中将 Realm 对象转换为 JSON?