Skip to content

Instantly share code, notes, and snippets.

@leoMehlig
Created October 18, 2017 21:13
Show Gist options
  • Select an option

  • Save leoMehlig/d325ce5890bbdd613a98cc022892aeba to your computer and use it in GitHub Desktop.

Select an option

Save leoMehlig/d325ce5890bbdd613a98cc022892aeba to your computer and use it in GitHub Desktop.
This is a workaround to parse an generic subelement of a json object. It just parses anything it finds. Currently supports Dictionary, Array, String, Int, Double, Bool.
/// This is a workaround to parse an generic subelement of a json object. It just parses anything it finds. Currently supports Dictionary, Array, String, Int, Double, Bool.struct AnyJSON: Decodable {
enum Error: Swift.Error {
case noContainter
case noSingleValue
}
struct CodingKeys: CodingKey {
var stringValue: String
init?(stringValue: String) {
self.stringValue = stringValue
}
var intValue: Int? { return nil }
init?(intValue: Int) { return nil }
}
let object: Any
func data() throws -> Data {
return try JSONSerialization.data(withJSONObject: self.object, options: [])
}
public init(from decoder: Decoder) throws {
if let container = try? decoder.container(keyedBy: CodingKeys.self) {
self.object = try Dictionary(container.allKeys.map({
($0.stringValue, try container.decode(AnyJSON.self, forKey: $0).object)
}), uniquingKeysWith: { $1 })
} else if var container = try? decoder.unkeyedContainer() {
var array = [Any]()
while !container.isAtEnd {
array.append(try container.decode(AnyJSON.self).object)
}
self.object = array
} else if let container = try? decoder.singleValueContainer() {
if let string = try? container.decode(String.self) {
self.object = string
} else if let int = try? container.decode(Int.self) {
self.object = int
} else if let double = try? container.decode(Double.self) {
self.object = double
} else if let bool = try? container.decode(Bool.self) {
self.object = bool
} else {
throw Error.noSingleValue
}
} else {
throw Error.noContainter
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment