Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A robust way to create JSON objects from JSONSerialization.
//
// 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
You can’t perform that action at this time.