-
Notifications
You must be signed in to change notification settings - Fork 1
/
JSONParser.swift
62 lines (51 loc) · 1.98 KB
/
JSONParser.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
import UIKit
func isDict(dict: AnyObject) -> Bool {
return dict.dynamicType.description() == NSDictionary().dynamicType.description() || dict.dynamicType.description() == "__NSCFDictionary"
}
func isArr(arr: AnyObject) -> Bool {
arr.dynamicType.description()
return arr.dynamicType.description() == NSArray().dynamicType.description() || arr.dynamicType.description() == "__NSCFArray"
}
class JSONParser {
static func jsonFromData(data: NSData) throws -> ([AnyObject],Dictionary<String, AnyObject>) {
var dict = Dictionary<String, AnyObject>()
var arr = [AnyObject]()
do {
let nsObj: AnyObject? = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableLeaves)
if isDict(nsObj!) {
dict = JSONParser.parseDict(nsObj as! NSDictionary)
} else if isArr(nsObj!) {
arr = JSONParser.parseArray(nsObj as! NSArray)
}
} catch let error as NSError {
throw error
}
return (arr,dict)
}
static func parseArray(nsArr: NSArray) -> Array<AnyObject> {
var arr = [AnyObject]()
for obj in nsArr {
if isDict(obj) {
arr.append(JSONParser.parseDict(obj as! NSDictionary))
} else if isArr(obj) {
arr.append(JSONParser.parseArray(obj as! NSArray))
} else {
arr.append(obj)
}
}
return arr
}
static func parseDict(nsDict: NSDictionary) -> Dictionary<String,AnyObject>{
var dict = Dictionary<String, AnyObject>()
for (key,value) in nsDict {
if isDict(value) {
dict[key as! String] = parseDict(value as! NSDictionary)
} else if isArr(value) {
dict[key as! String] = parseArray(value as! NSArray)
} else {
dict[key as! String] = value
}
}
return dict
}
}