Skip to content

Instantly share code, notes, and snippets.

@FranDepascuali
Created February 28, 2020 03:55
Show Gist options
  • Save FranDepascuali/bd0000fbb3497b0d463d7833511d18a9 to your computer and use it in GitHub Desktop.
Save FranDepascuali/bd0000fbb3497b0d463d7833511d18a9 to your computer and use it in GitHub Desktop.
Decode and encode complex json
import Foundation
let jsonString: String = """
{ "action": {"dynamicKey": [{"active": false}]},
"schedule": "00 09 * * 1,2,3,4,5",
"tz": "America.Chicago"}
"""
let jsonData = jsonString.data(using: .utf8)!
struct Action {
let timeZone: String
let schedule: String
let dynamicKeys: [String: Bool]
static func fromJSON(json: Data) -> Action? {
guard let encodedJSON = try? JSONSerialization.jsonObject(with: json, options: []) as? [String: Any] else {
return nil
}
guard
let timeZone = encodedJSON["tz"] as? String,
let schedule = encodedJSON["schedule"] as? String,
let actionJSON = encodedJSON["action"] as? [String: Any]
else {
return nil
}
let actions = decodeActions(rawActions: actionJSON)
return Action(timeZone: timeZone, schedule: schedule, dynamicKeys: actions)
}
func toJSON() -> Data? {
return try? JSONSerialization.data(
withJSONObject: [
"tz": timeZone,
"schedule": schedule,
"action": encodeActions(dynamicKeys: dynamicKeys)
],
options: .prettyPrinted)
}
}
func encodeActions(dynamicKeys: [String: Bool]) -> [String: [[String: Bool]]] {
return dynamicKeys.compactMapValues { isActive -> [[String: Bool]] in
return [["active": isActive]]
}
}
func decodeActions(rawActions: [String: Any]) -> [String: Bool] {
let actions = rawActions.compactMapValues { (value: Any) -> Bool? in
guard let value = value as? [[String: Bool]] else {
return nil
}
let activeValue = value
.compactMap { dictionary -> Bool? in
return dictionary["active"]
}
.first
return activeValue
}
return actions
}
func json(from object:Any) -> String? {
guard let data = try? JSONSerialization.data(withJSONObject: object, options: []) else {
return nil
}
return String(data: data, encoding: String.Encoding.utf8)
}
let action = Action.fromJSON(json: jsonData)!
let actionJson = action.toJSON()!
let actionAgain = Action.fromJSON(json: actionJson)
print(action)
print(actionJson)
print(actionAgain)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment