Files

48 lines
1.4 KiB
Swift

//
// NodeData.swift
//
// Created by NUT.TECH on 10.01.2023.
//
import Foundation
public struct NodeData: Decodable {
public let data: [String: Any]
public init(from decoder: Decoder) throws {
// Create a decoding container using DynamicCodingKeys
// The container will contain all the JSON first level key
let container = try decoder.container(keyedBy: DynamicCodingKeys.self)
var tempData = [String: Any]()
// Loop through each key
for key in container.allKeys {
if let value = try? container.decode(NodeData.self, forKey: key) {
tempData[key.stringValue] = value.data
} else if let value = try? container.decode(String.self, forKey: key) {
tempData[key.stringValue] = value
} else if let value = try? container.decode(Int.self, forKey: key) {
tempData[key.stringValue] = value
}
}
self.data = tempData
}
private struct DynamicCodingKeys: CodingKey {
// Use for string-keyed dictionary
var stringValue: String
init?(stringValue: String) {
self.stringValue = stringValue
}
// Use for integer-keyed dictionary
var intValue: Int?
init?(intValue: Int) {
// We are not using this, thus just return nil
return nil
}
}
}