我下面有json,我想从中解析/分配值
{
"Rooms":[
{
"id":"100",
"title":"CS Classroom",
"description":"Classroom for Computer science students",
"capacity":"50"
},
{
"id":"101",
"title":"Mechanical Lab",
"description":"Mechanical Lab work",
"capacity":"50"
},
{
"id":"108",
"title":"Computer Lab",
"description":"Computer Lab work",
"capacity":"50"
}
]
}
此json类型为[Dictionary:Dictonary],其中只有键“ Rooms”
在创建结构时,我应该创建
struct RoomsInfo: Decodable {
let rooms: Rooms
}
struct Rooms {
let id: String
let title: String
let description: String
let capacity: String
}
我的第一个问题是:由于我只有Rooms键,是否有可能只创建一个结构而不是两个结构?
我的第二个问题是:如果我的json具有“ Rooms1”,“ Rooms2”,“ Rooms3”,“ Rooms4”这样的键,在这种情况下,我可以创建确认可解码的结构还是需要手动解析它吗?
请指教
对于第一个问题,您有一个称为的密钥,Room
因此必须对其进行解码,是否可能不确定,而不是JSON
首先解析该数据以调出该密钥的值JSON["Rooms"]
,然后将其内部解析为[Room].self
,
对于第二个问题,如果计数是无限的,就好像您不知道要Room
计算多少键,那么Decoder
功能就受到限制,但是您始终可以将值映射为Dictionary
,然后将值解码为,Room
而无需关心关键,这个技巧可以解决,但是您将放弃原始的技巧Key
。
更新第二种情况:在下面查看此代码。
typealias jsonDictionary = [String: Any]
let jsonData = json.data(using: .utf8)! // converting test json string to data
var arrayOfRooms: [Room] = []
do {
let serialized = try JSONSerialization.jsonObject(with: jsonData, options: []) // serializing jsonData to json object
if let objects = serialized as? [String: Any] { //casting to dictionary
for key in objects.keys { //looping into the keys rooms (n) number
let rooms = objects[key] // getting those rooms by key
let data = try JSONSerialization.data(withJSONObject: rooms!, options: []) //converting those objects to data again to parse
var myRoom = try! JSONDecoder().decode([Room].self, from: data) // decoding each array of rooms
arrayOfRooms.append(contentsOf: myRoom) // appending rooms to main rooms array declared on top
print("Data", data) // just to check
}
print("MY Array Of Rooms Count \(arrayOfRooms.count)")
} else {
print("nil")
}
} catch {
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句