-
Notifications
You must be signed in to change notification settings - Fork 5
/
LumaJSON.swift
101 lines (81 loc) · 2.57 KB
/
LumaJSON.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
//
// LumaJSON.swift
// LumaJSON
//
// Created by Jameson Quave on 2/28/15.
// Copyright (c) 2015 Lumarow, LLC. All rights reserved.
//
import Foundation
class LumaJSONObject: Printable {
var value: AnyObject?
subscript(index: Int) -> LumaJSONObject? {
return (value as? [AnyObject]).map { LumaJSONObject($0[index]) }
}
subscript(key: String) -> LumaJSONObject? {
return (value as? NSDictionary).map { LumaJSONObject($0[key]) }
}
subscript(key: String) -> AnyObject? {
get {
return self[key]?.value
}
}
subscript(key: Int) -> AnyObject? {
get {
return self[key]?.value
}
}
init(_ value: AnyObject?) {
self.value = value
}
var description: String {
get {
return "LumaJSONObject: \(self.value)"
}
}
}
struct LumaJSON {
static var logErrors = true
static func jsonFromObject(object: [String: AnyObject]) -> String? {
var err: NSError?
if let jsonData = NSJSONSerialization.dataWithJSONObject( (object as NSDictionary) , options: nil, error: &err) {
if let jsonStr = NSString(data: jsonData, encoding: NSUTF8StringEncoding) {
return jsonStr as String
}
}
else if(err != nil) {
if LumaJSON.logErrors {
println( err?.localizedDescription )
}
}
return nil
}
static func parse(json: String) -> LumaJSONObject? {
if let jsonData = json.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false){
var err: NSError?
let parsed: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: .MutableLeaves, error: &err)
if let parsedArray = parsed as? NSArray {
return LumaJSONObject(parsedArray)
}
if let parsedDictionary = parsed as? NSDictionary {
return LumaJSONObject(parsedDictionary)
}
if LumaJSON.logErrors && (err != nil) {
println(err?.localizedDescription)
}
return LumaJSONObject(parsed)
}
return nil
}
}
extension String {
func toJSON() -> LumaJSONObject? {
return LumaJSON.parse(self)
}
init? (jsonDictionary: [String: AnyObject]) {
if let t = LumaJSON.jsonFromObject(jsonDictionary) {
self = t
} else {
return nil
}
}
}