Skip to content

Instantly share code, notes, and snippets.

@Vladlex
Created May 16, 2021 12:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Vladlex/5a8f7fc9b9d85dc87dfd5108ff6ba959 to your computer and use it in GitHub Desktop.
Save Vladlex/5a8f7fc9b9d85dc87dfd5108ff6ba959 to your computer and use it in GitHub Desktop.
JSONSmart - Simplified work with json
//
// 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