Created
May 16, 2021 12:31
-
-
Save Vladlex/5a8f7fc9b9d85dc87dfd5108ff6ba959 to your computer and use it in GitHub Desktop.
JSONSmart - Simplified work with json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// JSONSmart.swift | |
// | |
// | |
// Created by Aleksei Gordeev on 06.03.2021. | |
// | |
import Foundation | |
/// Simplifies the JSON content access. Inspired by SwiftyJSON. | |
internal struct JSONSmart { | |
let any: Any | |
var string: String? { | |
return any as? String | |
} | |
var int: Int? { | |
return any as? Int | |
} | |
var array: [Any]? { | |
return asArray(valueType: Any.self) | |
} | |
var dictionary: [String : Any]? { | |
return asDictionary(valueType: Any.self) | |
} | |
func asValue<ValueType>(ofType: ValueType.Type) -> ValueType? { | |
return any as? ValueType | |
} | |
init(any: Any) { | |
self.any = any | |
} | |
init(data: Data, options: JSONSerialization.ReadingOptions = []) throws { | |
self.any = try JSONSerialization.jsonObject(with: data, options: options) | |
} | |
subscript(index: Int) -> JSONSmart? { | |
return (asArray(valueType: Any.self)?[index]).flatMap({ JSONSmart(any: $0) }) | |
} | |
subscript(key: String) -> JSONSmart? { | |
return (asDictionary(valueType: Any.self)?[key]).flatMap({ JSONSmart(any: $0) }) | |
} | |
func asArray<E>(valueType: E.Type) -> [E]? { | |
return any as? [E] | |
} | |
func asDictionary<E>(valueType: E.Type) -> [String : E]? { | |
return any as? [String : E] | |
} | |
func get<S>(valueOfType valueType: S.Type, at idx: Int) -> S? { | |
return asArray(valueType: Any.self)?[idx] as? S | |
} | |
func get<S>(valueOfType valueType: S, for key: String) -> S? { | |
return asDictionary(valueType: Any.self)?[key] as? S | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment