我下面有一个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”这样的键,在这种情况下,我可以创建确认可解码的结构还是需要解析吗?手动吗?
请咨询
答案 0 :(得分:2)
对于第一个问题,您有一个名为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 {
}
答案 1 :(得分:0)
答案1:是的,nestedContainers
可以实现,但是付出的努力大于收益。
答案2:将字典解码为[String:Room]
或使用this answer中描述的自定义编码键