-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSONHandling.playground
More file actions
80 lines (67 loc) · 2.24 KB
/
JSONHandling.playground
File metadata and controls
80 lines (67 loc) · 2.24 KB
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
//Just download and open this file in Xcode to play with the code!
import UIKit
var str = "Hello, playground"
//Constants.swift
struct Constants {
static let userAppGroup = "B672DS45"
static let pathToJSON = "path/to/file"
struct Tables {
static let tools = "tools__c" //e.g. these fieldnames are how Salesforce custom fields are structured
static let accessories = "accessories__c"
struct ToolsKeys {
static let hammer = "hammer__c"
static let wrench = "wrench__c"
static let screwdriver = "screwdriver__c"
}
}
}
//sample.json
let jsonString: String =
"""
{
"tools__c": {
"hammer__c": "Stanley 5oz. Pro",
"screwdriver__c": "Craftsman 9-31794 Slotted Phillips"
},
"accessories__c": {
"nails__c": "nail brand"
}
}
"""
//JSONHandler.swift
typealias Tables = Constants.Tables
typealias Keys = Tables.ToolsKeys
class JSONHandler {
var json: Any?
var data: Data
var hammer = ""
public init(pathAsString: String) { //pass in the filepath of the JSON
var tempData: Data = Data()
do {
//tempData = try Data(contentsOf: URL(fileURLWithPath: pathAsString))
tempData = jsonString.data(using: .utf8)! //doing a bad thing (!) for demonstration purposes
}
catch {
print(error.localizedDescription)
}
self.data = tempData
self.json = try? JSONSerialization.jsonObject(with: self.data)
}
public func getTools() {
if let toolbox = json as? [String: Any] {
if let tools = toolbox[Tables.tools] as? [String: Any] {
if let hammer = tools[Keys.hammer], let screwdriver = tools[Keys.screwdriver] {
print("I have a hammer AND a wrench in my toolbox!")
}
//if we want to actually use the value, we need to tell the compiler what type we are expecting:
if let hammer = tools[Keys.hammer] as? String {
self.hammer = hammer
}
}
}
}
}
//Main.swift
let jsonHandler = JSONHandler(pathAsString: Constants.pathToJSON)
jsonHandler.getTools()
print("The hammer I have is a", jsonHandler.hammer)