Created
February 20, 2019 21:47
-
-
Save kvaDrug/fe71fe09a9e301a11e9c02903777220d to your computer and use it in GitHub Desktop.
A robust way to create JSON objects from JSONSerialization.
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
// | |
// Created by Vladimir Kelin on 2/8/19. | |
// Copyright © 2019 Systematix Infotech. All rights reserved. | |
// | |
/* | |
A more robust way to create JSON objects from JSONSerialization. | |
Why more robust? See the explanation: | |
http://kelindev.blogspot.com/2018/01/safer-parsing-with-jsonserialization-in.html | |
*/ | |
import Foundation | |
extension String { | |
init?(jsonObject: Any?) { | |
guard jsonObject is NSNull == false else { return nil } | |
let aNSObject = jsonObject as? NSObject | |
if let description = aNSObject?.description { | |
self = description | |
} else { | |
return nil | |
} | |
} | |
} | |
extension Int { | |
init?(jsonObject: Any?) { | |
if let number = jsonObject as? NSNumber { | |
self = number.intValue | |
} else if let string = jsonObject as? NSString { | |
self = string.integerValue | |
} else { | |
return nil | |
} | |
} | |
} | |
extension Int16 { | |
init?(jsonObject: Any?) { | |
if let number = jsonObject as? NSNumber { | |
self = number.int16Value | |
} else if let string = jsonObject as? NSString { | |
if let int16 = Int16(string as String) { | |
self = int16 | |
} else { | |
return nil | |
} | |
} else { | |
return nil | |
} | |
} | |
} | |
extension Int32 { | |
init?(jsonObject: Any?) { | |
if let number = jsonObject as? NSNumber { | |
self = number.int32Value | |
} else if let string = jsonObject as? NSString { | |
self = string.intValue | |
} else { | |
return nil | |
} | |
} | |
} | |
extension Bool { | |
init?(jsonObject: Any?) { | |
if let integer = Int(jsonObject: jsonObject) { | |
self = integer != 0 | |
} else { | |
return nil | |
} | |
} | |
} | |
extension Double { | |
init?(jsonObject: Any?) { | |
if let number = jsonObject as? NSNumber { | |
self = number.doubleValue | |
} else if let string = jsonObject as? NSString { | |
self = string.doubleValue | |
} else { | |
return nil | |
} | |
} | |
} | |
extension Float { | |
init?(jsonObject: Any?) { | |
if let number = jsonObject as? NSNumber { | |
self = number.floatValue | |
} else if let string = jsonObject as? NSString { | |
self = string.floatValue | |
} else { | |
return nil | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment