SwiftyJSON.swift 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352
  1. // SwiftyJSON.swift
  2. //
  3. // Copyright (c) 2014 Ruoyu Fu, Pinglin Tang
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. import Foundation
  23. // MARK: - Error
  24. ///Error domain
  25. public let ErrorDomain: String! = "SwiftyJSONErrorDomain"
  26. ///Error code
  27. public let ErrorUnsupportedType: Int! = 999
  28. public let ErrorIndexOutOfBounds: Int! = 900
  29. public let ErrorWrongType: Int! = 901
  30. public let ErrorNotExist: Int! = 500
  31. public let ErrorInvalidJSON: Int! = 490
  32. // MARK: - JSON Type
  33. /**
  34. JSON's type definitions.
  35. See http://tools.ietf.org/html/rfc7231#section-4.3
  36. */
  37. public enum Type :Int{
  38. case Number
  39. case String
  40. case Bool
  41. case Array
  42. case Dictionary
  43. case Null
  44. case Unknown
  45. }
  46. // MARK: - JSON Base
  47. public struct JSON {
  48. /**
  49. Creates a JSON using the data.
  50. - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary
  51. - parameter opt: The JSON serialization reading options. `.AllowFragments` by default.
  52. - parameter error: error The NSErrorPointer used to return the error. `nil` by default.
  53. - returns: The created JSON
  54. */
  55. public init(data:NSData, options opt: NSJSONReadingOptions = .AllowFragments, error: NSErrorPointer = nil) {
  56. do {
  57. let object: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: opt)
  58. self.init(object)
  59. } catch let aError as NSError {
  60. if error != nil {
  61. error.memory = aError
  62. }
  63. self.init(NSNull())
  64. }
  65. }
  66. /**
  67. Creates a JSON using the object.
  68. - parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity.
  69. - returns: The created JSON
  70. */
  71. public init(_ object: AnyObject) {
  72. self.object = object
  73. }
  74. /**
  75. Creates a JSON from a [JSON]
  76. - parameter jsonArray: A Swift array of JSON objects
  77. - returns: The created JSON
  78. */
  79. public init(_ jsonArray:[JSON]) {
  80. self.init(jsonArray.map { $0.object })
  81. }
  82. /**
  83. Creates a JSON from a [String: JSON]
  84. - parameter jsonDictionary: A Swift dictionary of JSON objects
  85. - returns: The created JSON
  86. */
  87. public init(_ jsonDictionary:[String: JSON]) {
  88. var dictionary = [String: AnyObject]()
  89. for (key, json) in jsonDictionary {
  90. dictionary[key] = json.object
  91. }
  92. self.init(dictionary)
  93. }
  94. /// Private object
  95. private var rawArray: [AnyObject] = []
  96. private var rawDictionary: [String : AnyObject] = [:]
  97. private var rawString: String = ""
  98. private var rawNumber: NSNumber = 0
  99. private var rawNull: NSNull = NSNull()
  100. /// Private type
  101. private var _type: Type = .Null
  102. /// prviate error
  103. private var _error: NSError? = nil
  104. /// Object in JSON
  105. public var object: AnyObject {
  106. get {
  107. switch self.type {
  108. case .Array:
  109. return self.rawArray
  110. case .Dictionary:
  111. return self.rawDictionary
  112. case .String:
  113. return self.rawString
  114. case .Number:
  115. return self.rawNumber
  116. case .Bool:
  117. return self.rawNumber
  118. default:
  119. return self.rawNull
  120. }
  121. }
  122. set {
  123. _error = nil
  124. switch newValue {
  125. case let number as NSNumber:
  126. if number.isBool {
  127. _type = .Bool
  128. } else {
  129. _type = .Number
  130. }
  131. self.rawNumber = number
  132. case let string as String:
  133. _type = .String
  134. self.rawString = string
  135. case _ as NSNull:
  136. _type = .Null
  137. case let array as [AnyObject]:
  138. _type = .Array
  139. self.rawArray = array
  140. case let dictionary as [String : AnyObject]:
  141. _type = .Dictionary
  142. self.rawDictionary = dictionary
  143. default:
  144. _type = .Unknown
  145. _error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"])
  146. }
  147. }
  148. }
  149. /// json type
  150. public var type: Type { get { return _type } }
  151. /// Error in JSON
  152. public var error: NSError? { get { return self._error } }
  153. /// The static null json
  154. @available(*, unavailable, renamed="null")
  155. public static var nullJSON: JSON { get { return null } }
  156. public static var null: JSON { get { return JSON(NSNull()) } }
  157. }
  158. // MARK: - CollectionType, SequenceType, Indexable
  159. extension JSON : Swift.CollectionType, Swift.SequenceType, Swift.Indexable {
  160. public typealias Generator = JSONGenerator
  161. public typealias Index = JSONIndex
  162. public var startIndex: JSON.Index {
  163. switch self.type {
  164. case .Array:
  165. return JSONIndex(arrayIndex: self.rawArray.startIndex)
  166. case .Dictionary:
  167. return JSONIndex(dictionaryIndex: self.rawDictionary.startIndex)
  168. default:
  169. return JSONIndex()
  170. }
  171. }
  172. public var endIndex: JSON.Index {
  173. switch self.type {
  174. case .Array:
  175. return JSONIndex(arrayIndex: self.rawArray.endIndex)
  176. case .Dictionary:
  177. return JSONIndex(dictionaryIndex: self.rawDictionary.endIndex)
  178. default:
  179. return JSONIndex()
  180. }
  181. }
  182. public subscript (position: JSON.Index) -> JSON.Generator.Element {
  183. switch self.type {
  184. case .Array:
  185. return (String(position.arrayIndex), JSON(self.rawArray[position.arrayIndex!]))
  186. case .Dictionary:
  187. let (key, value) = self.rawDictionary[position.dictionaryIndex!]
  188. return (key, JSON(value))
  189. default:
  190. return ("", JSON.null)
  191. }
  192. }
  193. /// If `type` is `.Array` or `.Dictionary`, return `array.empty` or `dictonary.empty` otherwise return `false`.
  194. public var isEmpty: Bool {
  195. get {
  196. switch self.type {
  197. case .Array:
  198. return self.rawArray.isEmpty
  199. case .Dictionary:
  200. return self.rawDictionary.isEmpty
  201. default:
  202. return true
  203. }
  204. }
  205. }
  206. /// If `type` is `.Array` or `.Dictionary`, return `array.count` or `dictonary.count` otherwise return `0`.
  207. public var count: Int {
  208. switch self.type {
  209. case .Array:
  210. return self.rawArray.count
  211. case .Dictionary:
  212. return self.rawDictionary.count
  213. default:
  214. return 0
  215. }
  216. }
  217. public func underestimateCount() -> Int {
  218. switch self.type {
  219. case .Array:
  220. return self.rawArray.underestimateCount()
  221. case .Dictionary:
  222. return self.rawDictionary.underestimateCount()
  223. default:
  224. return 0
  225. }
  226. }
  227. /**
  228. If `type` is `.Array` or `.Dictionary`, return a generator over the elements like `Array` or `Dictionary`, otherwise return a generator over empty.
  229. - returns: Return a *generator* over the elements of JSON.
  230. */
  231. public func generate() -> JSON.Generator {
  232. return JSON.Generator(self)
  233. }
  234. }
  235. public struct JSONIndex: ForwardIndexType, _Incrementable, Equatable, Comparable {
  236. let arrayIndex: Int?
  237. let dictionaryIndex: DictionaryIndex<String, AnyObject>?
  238. let type: Type
  239. init(){
  240. self.arrayIndex = nil
  241. self.dictionaryIndex = nil
  242. self.type = .Unknown
  243. }
  244. init(arrayIndex: Int) {
  245. self.arrayIndex = arrayIndex
  246. self.dictionaryIndex = nil
  247. self.type = .Array
  248. }
  249. init(dictionaryIndex: DictionaryIndex<String, AnyObject>) {
  250. self.arrayIndex = nil
  251. self.dictionaryIndex = dictionaryIndex
  252. self.type = .Dictionary
  253. }
  254. public func successor() -> JSONIndex {
  255. switch self.type {
  256. case .Array:
  257. return JSONIndex(arrayIndex: self.arrayIndex!.successor())
  258. case .Dictionary:
  259. return JSONIndex(dictionaryIndex: self.dictionaryIndex!.successor())
  260. default:
  261. return JSONIndex()
  262. }
  263. }
  264. }
  265. public func ==(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
  266. switch (lhs.type, rhs.type) {
  267. case (.Array, .Array):
  268. return lhs.arrayIndex == rhs.arrayIndex
  269. case (.Dictionary, .Dictionary):
  270. return lhs.dictionaryIndex == rhs.dictionaryIndex
  271. default:
  272. return false
  273. }
  274. }
  275. public func <(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
  276. switch (lhs.type, rhs.type) {
  277. case (.Array, .Array):
  278. return lhs.arrayIndex < rhs.arrayIndex
  279. case (.Dictionary, .Dictionary):
  280. return lhs.dictionaryIndex < rhs.dictionaryIndex
  281. default:
  282. return false
  283. }
  284. }
  285. public func <=(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
  286. switch (lhs.type, rhs.type) {
  287. case (.Array, .Array):
  288. return lhs.arrayIndex <= rhs.arrayIndex
  289. case (.Dictionary, .Dictionary):
  290. return lhs.dictionaryIndex <= rhs.dictionaryIndex
  291. default:
  292. return false
  293. }
  294. }
  295. public func >=(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
  296. switch (lhs.type, rhs.type) {
  297. case (.Array, .Array):
  298. return lhs.arrayIndex >= rhs.arrayIndex
  299. case (.Dictionary, .Dictionary):
  300. return lhs.dictionaryIndex >= rhs.dictionaryIndex
  301. default:
  302. return false
  303. }
  304. }
  305. public func >(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
  306. switch (lhs.type, rhs.type) {
  307. case (.Array, .Array):
  308. return lhs.arrayIndex > rhs.arrayIndex
  309. case (.Dictionary, .Dictionary):
  310. return lhs.dictionaryIndex > rhs.dictionaryIndex
  311. default:
  312. return false
  313. }
  314. }
  315. public struct JSONGenerator : GeneratorType {
  316. public typealias Element = (String, JSON)
  317. private let type: Type
  318. private var dictionayGenerate: DictionaryGenerator<String, AnyObject>?
  319. private var arrayGenerate: IndexingGenerator<[AnyObject]>?
  320. private var arrayIndex: Int = 0
  321. init(_ json: JSON) {
  322. self.type = json.type
  323. if type == .Array {
  324. self.arrayGenerate = json.rawArray.generate()
  325. }else {
  326. self.dictionayGenerate = json.rawDictionary.generate()
  327. }
  328. }
  329. public mutating func next() -> JSONGenerator.Element? {
  330. switch self.type {
  331. case .Array:
  332. if let o = self.arrayGenerate!.next() {
  333. return (String(self.arrayIndex++), JSON(o))
  334. } else {
  335. return nil
  336. }
  337. case .Dictionary:
  338. if let (k, v): (String, AnyObject) = self.dictionayGenerate!.next() {
  339. return (k, JSON(v))
  340. } else {
  341. return nil
  342. }
  343. default:
  344. return nil
  345. }
  346. }
  347. }
  348. // MARK: - Subscript
  349. /**
  350. * To mark both String and Int can be used in subscript.
  351. */
  352. public protocol JSONSubscriptType {}
  353. extension Int: JSONSubscriptType {}
  354. extension String: JSONSubscriptType {}
  355. extension JSON {
  356. /// If `type` is `.Array`, return json which's object is `array[index]`, otherwise return null json with error.
  357. private subscript(index index: Int) -> JSON {
  358. get {
  359. if self.type != .Array {
  360. var r = JSON.null
  361. r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"])
  362. return r
  363. } else if index >= 0 && index < self.rawArray.count {
  364. return JSON(self.rawArray[index])
  365. } else {
  366. var r = JSON.null
  367. r._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"])
  368. return r
  369. }
  370. }
  371. set {
  372. if self.type == .Array {
  373. if self.rawArray.count > index && newValue.error == nil {
  374. self.rawArray[index] = newValue.object
  375. }
  376. }
  377. }
  378. }
  379. /// If `type` is `.Dictionary`, return json which's object is `dictionary[key]` , otherwise return null json with error.
  380. private subscript(key key: String) -> JSON {
  381. get {
  382. var r = JSON.null
  383. if self.type == .Dictionary {
  384. if let o = self.rawDictionary[key] {
  385. r = JSON(o)
  386. } else {
  387. r._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"])
  388. }
  389. } else {
  390. r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"])
  391. }
  392. return r
  393. }
  394. set {
  395. if self.type == .Dictionary && newValue.error == nil {
  396. self.rawDictionary[key] = newValue.object
  397. }
  398. }
  399. }
  400. /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`.
  401. private subscript(sub sub: JSONSubscriptType) -> JSON {
  402. get {
  403. if sub is String {
  404. return self[key:sub as! String]
  405. } else {
  406. return self[index:sub as! Int]
  407. }
  408. }
  409. set {
  410. if sub is String {
  411. self[key:sub as! String] = newValue
  412. } else {
  413. self[index:sub as! Int] = newValue
  414. }
  415. }
  416. }
  417. /**
  418. Find a json in the complex data structuresby using the Int/String's array.
  419. - parameter path: The target json's path. Example:
  420. let json = JSON[data]
  421. let path = [9,"list","person","name"]
  422. let name = json[path]
  423. The same as: let name = json[9]["list"]["person"]["name"]
  424. - returns: Return a json found by the path or a null json with error
  425. */
  426. public subscript(path: [JSONSubscriptType]) -> JSON {
  427. get {
  428. return path.reduce(self) { $0[sub: $1] }
  429. }
  430. set {
  431. switch path.count {
  432. case 0:
  433. return
  434. case 1:
  435. self[sub:path[0]].object = newValue.object
  436. default:
  437. var aPath = path; aPath.removeAtIndex(0)
  438. var nextJSON = self[sub: path[0]]
  439. nextJSON[aPath] = newValue
  440. self[sub: path[0]] = nextJSON
  441. }
  442. }
  443. }
  444. /**
  445. Find a json in the complex data structuresby using the Int/String's array.
  446. - parameter path: The target json's path. Example:
  447. let name = json[9,"list","person","name"]
  448. The same as: let name = json[9]["list"]["person"]["name"]
  449. - returns: Return a json found by the path or a null json with error
  450. */
  451. public subscript(path: JSONSubscriptType...) -> JSON {
  452. get {
  453. return self[path]
  454. }
  455. set {
  456. self[path] = newValue
  457. }
  458. }
  459. }
  460. // MARK: - LiteralConvertible
  461. extension JSON: Swift.StringLiteralConvertible {
  462. public init(stringLiteral value: StringLiteralType) {
  463. self.init(value)
  464. }
  465. public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
  466. self.init(value)
  467. }
  468. public init(unicodeScalarLiteral value: StringLiteralType) {
  469. self.init(value)
  470. }
  471. }
  472. extension JSON: Swift.IntegerLiteralConvertible {
  473. public init(integerLiteral value: IntegerLiteralType) {
  474. self.init(value)
  475. }
  476. }
  477. extension JSON: Swift.BooleanLiteralConvertible {
  478. public init(booleanLiteral value: BooleanLiteralType) {
  479. self.init(value)
  480. }
  481. }
  482. extension JSON: Swift.FloatLiteralConvertible {
  483. public init(floatLiteral value: FloatLiteralType) {
  484. self.init(value)
  485. }
  486. }
  487. extension JSON: Swift.DictionaryLiteralConvertible {
  488. public init(dictionaryLiteral elements: (String, AnyObject)...) {
  489. self.init(elements.reduce([String : AnyObject]()){(dictionary: [String : AnyObject], element:(String, AnyObject)) -> [String : AnyObject] in
  490. var d = dictionary
  491. d[element.0] = element.1
  492. return d
  493. })
  494. }
  495. }
  496. extension JSON: Swift.ArrayLiteralConvertible {
  497. public init(arrayLiteral elements: AnyObject...) {
  498. self.init(elements)
  499. }
  500. }
  501. extension JSON: Swift.NilLiteralConvertible {
  502. public init(nilLiteral: ()) {
  503. self.init(NSNull())
  504. }
  505. }
  506. // MARK: - Raw
  507. extension JSON: Swift.RawRepresentable {
  508. public init?(rawValue: AnyObject) {
  509. if JSON(rawValue).type == .Unknown {
  510. return nil
  511. } else {
  512. self.init(rawValue)
  513. }
  514. }
  515. public var rawValue: AnyObject {
  516. return self.object
  517. }
  518. public func rawData(options opt: NSJSONWritingOptions = NSJSONWritingOptions(rawValue: 0)) throws -> NSData {
  519. guard NSJSONSerialization.isValidJSONObject(self.object) else {
  520. throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "JSON is invalid"])
  521. }
  522. return try NSJSONSerialization.dataWithJSONObject(self.object, options: opt)
  523. }
  524. public func rawString(encoding: UInt = NSUTF8StringEncoding, options opt: NSJSONWritingOptions = .PrettyPrinted) -> String? {
  525. switch self.type {
  526. case .Array, .Dictionary:
  527. do {
  528. let data = try self.rawData(options: opt)
  529. return NSString(data: data, encoding: encoding) as? String
  530. } catch _ {
  531. return nil
  532. }
  533. case .String:
  534. return self.rawString
  535. case .Number:
  536. return self.rawNumber.stringValue
  537. case .Bool:
  538. return self.rawNumber.boolValue.description
  539. case .Null:
  540. return "null"
  541. default:
  542. return nil
  543. }
  544. }
  545. }
  546. // MARK: - Printable, DebugPrintable
  547. extension JSON: Swift.Printable, Swift.DebugPrintable {
  548. public var description: String {
  549. if let string = self.rawString(options:.PrettyPrinted) {
  550. return string
  551. } else {
  552. return "unknown"
  553. }
  554. }
  555. public var debugDescription: String {
  556. return description
  557. }
  558. }
  559. // MARK: - Array
  560. extension JSON {
  561. //Optional [JSON]
  562. public var array: [JSON]? {
  563. get {
  564. if self.type == .Array {
  565. return self.rawArray.map{ JSON($0) }
  566. } else {
  567. return nil
  568. }
  569. }
  570. }
  571. //Non-optional [JSON]
  572. public var arrayValue: [JSON] {
  573. get {
  574. return self.array ?? []
  575. }
  576. }
  577. //Optional [AnyObject]
  578. public var arrayObject: [AnyObject]? {
  579. get {
  580. switch self.type {
  581. case .Array:
  582. return self.rawArray
  583. default:
  584. return nil
  585. }
  586. }
  587. set {
  588. if let array = newValue {
  589. self.object = array
  590. } else {
  591. self.object = NSNull()
  592. }
  593. }
  594. }
  595. }
  596. // MARK: - Dictionary
  597. extension JSON {
  598. //Optional [String : JSON]
  599. public var dictionary: [String : JSON]? {
  600. if self.type == .Dictionary {
  601. return self.rawDictionary.reduce([String : JSON]()) { (dictionary: [String : JSON], element: (String, AnyObject)) -> [String : JSON] in
  602. var d = dictionary
  603. d[element.0] = JSON(element.1)
  604. return d
  605. }
  606. } else {
  607. return nil
  608. }
  609. }
  610. //Non-optional [String : JSON]
  611. public var dictionaryValue: [String : JSON] {
  612. return self.dictionary ?? [:]
  613. }
  614. //Optional [String : AnyObject]
  615. public var dictionaryObject: [String : AnyObject]? {
  616. get {
  617. switch self.type {
  618. case .Dictionary:
  619. return self.rawDictionary
  620. default:
  621. return nil
  622. }
  623. }
  624. set {
  625. if let v = newValue {
  626. self.object = v
  627. } else {
  628. self.object = NSNull()
  629. }
  630. }
  631. }
  632. }
  633. // MARK: - Bool
  634. extension JSON: Swift.BooleanType {
  635. //Optional bool
  636. public var bool: Bool? {
  637. get {
  638. switch self.type {
  639. case .Bool:
  640. return self.rawNumber.boolValue
  641. default:
  642. return nil
  643. }
  644. }
  645. set {
  646. if newValue != nil {
  647. self.object = NSNumber(bool: newValue!)
  648. } else {
  649. self.object = NSNull()
  650. }
  651. }
  652. }
  653. //Non-optional bool
  654. public var boolValue: Bool {
  655. get {
  656. switch self.type {
  657. case .Bool, .Number, .String:
  658. return self.object.boolValue
  659. default:
  660. return false
  661. }
  662. }
  663. set {
  664. self.object = NSNumber(bool: newValue)
  665. }
  666. }
  667. }
  668. // MARK: - String
  669. extension JSON {
  670. //Optional string
  671. public var string: String? {
  672. get {
  673. switch self.type {
  674. case .String:
  675. return self.object as? String
  676. default:
  677. return nil
  678. }
  679. }
  680. set {
  681. if newValue != nil {
  682. self.object = NSString(string:newValue!)
  683. } else {
  684. self.object = NSNull()
  685. }
  686. }
  687. }
  688. //Non-optional string
  689. public var stringValue: String {
  690. get {
  691. switch self.type {
  692. case .String:
  693. return self.object as! String
  694. case .Number:
  695. return self.object.stringValue
  696. case .Bool:
  697. return (self.object as! Bool).description
  698. default:
  699. return ""
  700. }
  701. }
  702. set {
  703. self.object = NSString(string:newValue)
  704. }
  705. }
  706. }
  707. // MARK: - Number
  708. extension JSON {
  709. //Optional number
  710. public var number: NSNumber? {
  711. get {
  712. switch self.type {
  713. case .Number, .Bool:
  714. return self.rawNumber
  715. default:
  716. return nil
  717. }
  718. }
  719. set {
  720. self.object = newValue ?? NSNull()
  721. }
  722. }
  723. //Non-optional number
  724. public var numberValue: NSNumber {
  725. get {
  726. switch self.type {
  727. case .String:
  728. let decimal = NSDecimalNumber(string: self.object as? String)
  729. if decimal == NSDecimalNumber.notANumber() { // indicates parse error
  730. return NSDecimalNumber.zero()
  731. }
  732. return decimal
  733. case .Number, .Bool:
  734. return self.object as! NSNumber
  735. default:
  736. return NSNumber(double: 0.0)
  737. }
  738. }
  739. set {
  740. self.object = newValue
  741. }
  742. }
  743. }
  744. //MARK: - Null
  745. extension JSON {
  746. public var null: NSNull? {
  747. get {
  748. switch self.type {
  749. case .Null:
  750. return self.rawNull
  751. default:
  752. return nil
  753. }
  754. }
  755. set {
  756. self.object = NSNull()
  757. }
  758. }
  759. public func isExists() -> Bool{
  760. if let errorValue = error where errorValue.code == ErrorNotExist{
  761. return false
  762. }
  763. return true
  764. }
  765. }
  766. //MARK: - URL
  767. extension JSON {
  768. //Optional URL
  769. public var URL: NSURL? {
  770. get {
  771. switch self.type {
  772. case .String:
  773. if let encodedString_ = self.rawString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) {
  774. return NSURL(string: encodedString_)
  775. } else {
  776. return nil
  777. }
  778. default:
  779. return nil
  780. }
  781. }
  782. set {
  783. self.object = newValue?.absoluteString ?? NSNull()
  784. }
  785. }
  786. }
  787. // MARK: - Int, Double, Float, Int8, Int16, Int32, Int64
  788. extension JSON {
  789. public var double: Double? {
  790. get {
  791. return self.number?.doubleValue
  792. }
  793. set {
  794. if newValue != nil {
  795. self.object = NSNumber(double: newValue!)
  796. } else {
  797. self.object = NSNull()
  798. }
  799. }
  800. }
  801. public var doubleValue: Double {
  802. get {
  803. return self.numberValue.doubleValue
  804. }
  805. set {
  806. self.object = NSNumber(double: newValue)
  807. }
  808. }
  809. public var float: Float? {
  810. get {
  811. return self.number?.floatValue
  812. }
  813. set {
  814. if newValue != nil {
  815. self.object = NSNumber(float: newValue!)
  816. } else {
  817. self.object = NSNull()
  818. }
  819. }
  820. }
  821. public var floatValue: Float {
  822. get {
  823. return self.numberValue.floatValue
  824. }
  825. set {
  826. self.object = NSNumber(float: newValue)
  827. }
  828. }
  829. public var int: Int? {
  830. get {
  831. return self.number?.longValue
  832. }
  833. set {
  834. if newValue != nil {
  835. self.object = NSNumber(integer: newValue!)
  836. } else {
  837. self.object = NSNull()
  838. }
  839. }
  840. }
  841. public var intValue: Int {
  842. get {
  843. return self.numberValue.integerValue
  844. }
  845. set {
  846. self.object = NSNumber(integer: newValue)
  847. }
  848. }
  849. public var uInt: UInt? {
  850. get {
  851. return self.number?.unsignedLongValue
  852. }
  853. set {
  854. if newValue != nil {
  855. self.object = NSNumber(unsignedLong: newValue!)
  856. } else {
  857. self.object = NSNull()
  858. }
  859. }
  860. }
  861. public var uIntValue: UInt {
  862. get {
  863. return self.numberValue.unsignedLongValue
  864. }
  865. set {
  866. self.object = NSNumber(unsignedLong: newValue)
  867. }
  868. }
  869. public var int8: Int8? {
  870. get {
  871. return self.number?.charValue
  872. }
  873. set {
  874. if newValue != nil {
  875. self.object = NSNumber(char: newValue!)
  876. } else {
  877. self.object = NSNull()
  878. }
  879. }
  880. }
  881. public var int8Value: Int8 {
  882. get {
  883. return self.numberValue.charValue
  884. }
  885. set {
  886. self.object = NSNumber(char: newValue)
  887. }
  888. }
  889. public var uInt8: UInt8? {
  890. get {
  891. return self.number?.unsignedCharValue
  892. }
  893. set {
  894. if newValue != nil {
  895. self.object = NSNumber(unsignedChar: newValue!)
  896. } else {
  897. self.object = NSNull()
  898. }
  899. }
  900. }
  901. public var uInt8Value: UInt8 {
  902. get {
  903. return self.numberValue.unsignedCharValue
  904. }
  905. set {
  906. self.object = NSNumber(unsignedChar: newValue)
  907. }
  908. }
  909. public var int16: Int16? {
  910. get {
  911. return self.number?.shortValue
  912. }
  913. set {
  914. if newValue != nil {
  915. self.object = NSNumber(short: newValue!)
  916. } else {
  917. self.object = NSNull()
  918. }
  919. }
  920. }
  921. public var int16Value: Int16 {
  922. get {
  923. return self.numberValue.shortValue
  924. }
  925. set {
  926. self.object = NSNumber(short: newValue)
  927. }
  928. }
  929. public var uInt16: UInt16? {
  930. get {
  931. return self.number?.unsignedShortValue
  932. }
  933. set {
  934. if newValue != nil {
  935. self.object = NSNumber(unsignedShort: newValue!)
  936. } else {
  937. self.object = NSNull()
  938. }
  939. }
  940. }
  941. public var uInt16Value: UInt16 {
  942. get {
  943. return self.numberValue.unsignedShortValue
  944. }
  945. set {
  946. self.object = NSNumber(unsignedShort: newValue)
  947. }
  948. }
  949. public var int32: Int32? {
  950. get {
  951. return self.number?.intValue
  952. }
  953. set {
  954. if newValue != nil {
  955. self.object = NSNumber(int: newValue!)
  956. } else {
  957. self.object = NSNull()
  958. }
  959. }
  960. }
  961. public var int32Value: Int32 {
  962. get {
  963. return self.numberValue.intValue
  964. }
  965. set {
  966. self.object = NSNumber(int: newValue)
  967. }
  968. }
  969. public var uInt32: UInt32? {
  970. get {
  971. return self.number?.unsignedIntValue
  972. }
  973. set {
  974. if newValue != nil {
  975. self.object = NSNumber(unsignedInt: newValue!)
  976. } else {
  977. self.object = NSNull()
  978. }
  979. }
  980. }
  981. public var uInt32Value: UInt32 {
  982. get {
  983. return self.numberValue.unsignedIntValue
  984. }
  985. set {
  986. self.object = NSNumber(unsignedInt: newValue)
  987. }
  988. }
  989. public var int64: Int64? {
  990. get {
  991. return self.number?.longLongValue
  992. }
  993. set {
  994. if newValue != nil {
  995. self.object = NSNumber(longLong: newValue!)
  996. } else {
  997. self.object = NSNull()
  998. }
  999. }
  1000. }
  1001. public var int64Value: Int64 {
  1002. get {
  1003. return self.numberValue.longLongValue
  1004. }
  1005. set {
  1006. self.object = NSNumber(longLong: newValue)
  1007. }
  1008. }
  1009. public var uInt64: UInt64? {
  1010. get {
  1011. return self.number?.unsignedLongLongValue
  1012. }
  1013. set {
  1014. if newValue != nil {
  1015. self.object = NSNumber(unsignedLongLong: newValue!)
  1016. } else {
  1017. self.object = NSNull()
  1018. }
  1019. }
  1020. }
  1021. public var uInt64Value: UInt64 {
  1022. get {
  1023. return self.numberValue.unsignedLongLongValue
  1024. }
  1025. set {
  1026. self.object = NSNumber(unsignedLongLong: newValue)
  1027. }
  1028. }
  1029. }
  1030. //MARK: - Comparable
  1031. extension JSON : Swift.Comparable {}
  1032. public func ==(lhs: JSON, rhs: JSON) -> Bool {
  1033. switch (lhs.type, rhs.type) {
  1034. case (.Number, .Number):
  1035. return lhs.rawNumber == rhs.rawNumber
  1036. case (.String, .String):
  1037. return lhs.rawString == rhs.rawString
  1038. case (.Bool, .Bool):
  1039. return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue
  1040. case (.Array, .Array):
  1041. return lhs.rawArray as NSArray == rhs.rawArray as NSArray
  1042. case (.Dictionary, .Dictionary):
  1043. return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
  1044. case (.Null, .Null):
  1045. return true
  1046. default:
  1047. return false
  1048. }
  1049. }
  1050. public func <=(lhs: JSON, rhs: JSON) -> Bool {
  1051. switch (lhs.type, rhs.type) {
  1052. case (.Number, .Number):
  1053. return lhs.rawNumber <= rhs.rawNumber
  1054. case (.String, .String):
  1055. return lhs.rawString <= rhs.rawString
  1056. case (.Bool, .Bool):
  1057. return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue
  1058. case (.Array, .Array):
  1059. return lhs.rawArray as NSArray == rhs.rawArray as NSArray
  1060. case (.Dictionary, .Dictionary):
  1061. return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
  1062. case (.Null, .Null):
  1063. return true
  1064. default:
  1065. return false
  1066. }
  1067. }
  1068. public func >=(lhs: JSON, rhs: JSON) -> Bool {
  1069. switch (lhs.type, rhs.type) {
  1070. case (.Number, .Number):
  1071. return lhs.rawNumber >= rhs.rawNumber
  1072. case (.String, .String):
  1073. return lhs.rawString >= rhs.rawString
  1074. case (.Bool, .Bool):
  1075. return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue
  1076. case (.Array, .Array):
  1077. return lhs.rawArray as NSArray == rhs.rawArray as NSArray
  1078. case (.Dictionary, .Dictionary):
  1079. return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
  1080. case (.Null, .Null):
  1081. return true
  1082. default:
  1083. return false
  1084. }
  1085. }
  1086. public func >(lhs: JSON, rhs: JSON) -> Bool {
  1087. switch (lhs.type, rhs.type) {
  1088. case (.Number, .Number):
  1089. return lhs.rawNumber > rhs.rawNumber
  1090. case (.String, .String):
  1091. return lhs.rawString > rhs.rawString
  1092. default:
  1093. return false
  1094. }
  1095. }
  1096. public func <(lhs: JSON, rhs: JSON) -> Bool {
  1097. switch (lhs.type, rhs.type) {
  1098. case (.Number, .Number):
  1099. return lhs.rawNumber < rhs.rawNumber
  1100. case (.String, .String):
  1101. return lhs.rawString < rhs.rawString
  1102. default:
  1103. return false
  1104. }
  1105. }
  1106. private let trueNumber = NSNumber(bool: true)
  1107. private let falseNumber = NSNumber(bool: false)
  1108. private let trueObjCType = String.fromCString(trueNumber.objCType)
  1109. private let falseObjCType = String.fromCString(falseNumber.objCType)
  1110. // MARK: - NSNumber: Comparable
  1111. extension NSNumber {
  1112. var isBool:Bool {
  1113. get {
  1114. let objCType = String.fromCString(self.objCType)
  1115. if (self.compare(trueNumber) == NSComparisonResult.OrderedSame && objCType == trueObjCType)
  1116. || (self.compare(falseNumber) == NSComparisonResult.OrderedSame && objCType == falseObjCType){
  1117. return true
  1118. } else {
  1119. return false
  1120. }
  1121. }
  1122. }
  1123. }
  1124. public func ==(lhs: NSNumber, rhs: NSNumber) -> Bool {
  1125. switch (lhs.isBool, rhs.isBool) {
  1126. case (false, true):
  1127. return false
  1128. case (true, false):
  1129. return false
  1130. default:
  1131. return lhs.compare(rhs) == NSComparisonResult.OrderedSame
  1132. }
  1133. }
  1134. public func !=(lhs: NSNumber, rhs: NSNumber) -> Bool {
  1135. return !(lhs == rhs)
  1136. }
  1137. public func <(lhs: NSNumber, rhs: NSNumber) -> Bool {
  1138. switch (lhs.isBool, rhs.isBool) {
  1139. case (false, true):
  1140. return false
  1141. case (true, false):
  1142. return false
  1143. default:
  1144. return lhs.compare(rhs) == NSComparisonResult.OrderedAscending
  1145. }
  1146. }
  1147. public func >(lhs: NSNumber, rhs: NSNumber) -> Bool {
  1148. switch (lhs.isBool, rhs.isBool) {
  1149. case (false, true):
  1150. return false
  1151. case (true, false):
  1152. return false
  1153. default:
  1154. return lhs.compare(rhs) == NSComparisonResult.OrderedDescending
  1155. }
  1156. }
  1157. public func <=(lhs: NSNumber, rhs: NSNumber) -> Bool {
  1158. switch (lhs.isBool, rhs.isBool) {
  1159. case (false, true):
  1160. return false
  1161. case (true, false):
  1162. return false
  1163. default:
  1164. return lhs.compare(rhs) != NSComparisonResult.OrderedDescending
  1165. }
  1166. }
  1167. public func >=(lhs: NSNumber, rhs: NSNumber) -> Bool {
  1168. switch (lhs.isBool, rhs.isBool) {
  1169. case (false, true):
  1170. return false
  1171. case (true, false):
  1172. return false
  1173. default:
  1174. return lhs.compare(rhs) != NSComparisonResult.OrderedAscending
  1175. }
  1176. }