-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJSONBox7
297 lines (221 loc) · 10.6 KB
/
JSONBox7
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
//Sorry it took me a while to get this up! This goes in the ViewController.swift file.
// ViewController.swift
// JSON(Box7)
//
// Created by Robert Leon Collins Jr on 10/10/15.
// Copyright © 2015 Robert Leon Collins Jr. All rights reserved.
//
import UIKit
import Foundation
class ViewController: UIViewController {
@IBOutlet var button: UIButton!
override func viewDidLoad() {
////////////////////////////////
//Good Code to Parse JSON
////////////////////////////////
//JSON with numbers
let NumberJSON = "[0,6,7,13,69,100]"
let data = NumberJSON.dataUsingEncoding(NSUTF8StringEncoding)!
do {
guard let pasedObject: AnyObject? = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0) ) else {
print("Failure")
return
}
print("Here is teh JSON String: \(pasedObject!)")
}
catch let error {
print("Bad Json path \(error)")
}
////////////////////////////////////////////////////
//Good code for Stringify
/////////////////////////////////////////////////////
/*
The following code is good code for JSON stringify to print JSON or objects as a String and also how to use "prettyPrinted"
*/
let jsonObject: [AnyObject] = [
["position": "Teacher", "ageRange": "25-65"],
["position": "Student", "ageRange": "5-24"],
]
func JSONStringify(value: AnyObject,prettyPrinted:Bool = false) -> String{
let options = prettyPrinted ? NSJSONWritingOptions.PrettyPrinted : NSJSONWritingOptions(rawValue: 0)
if NSJSONSerialization.isValidJSONObject(value) {
do{
let data = try NSJSONSerialization.dataWithJSONObject(value, options: options)
if let string = NSString(data: data, encoding: NSUTF8StringEncoding) {
return string as String
}
}catch {
print("error")
}
}
return ""
}
//This just prints out a normal string that has all the data of hte object.
let jsonString = JSONStringify(jsonObject)
print(jsonString)
//This uses pretty printed which will pring the same info as the one above but prints it out so it is easier to show.
let jsonStringPretty = JSONStringify(jsonObject, prettyPrinted: true)
print(jsonStringPretty)
//////////////////////
// Good Code for Web API call
//////////////////////
let webApi = NSURL(fileURLWithPath: "api.openweathermap.org/data/2.5/weather?id=2172797&APPID=812dea426248df463a3804bcadb71fca")
print("This is a web API: \(webApi)")
do {
let webData = NSData(contentsOfURL: webApi)
var printTheData = try NSJSONSerialization.JSONObjectWithData(webData!, options: NSJSONReadingOptions.MutableContainers)
print(printTheData)
} catch let errorParse {
print("You made a mistake! \(errorParse)")
}
/////////////////////////////////////////////////////
//NASTY PATHS FOR JSON
/////////////////////////////////////////////////////
/*
//This attempts to call item 0 in the "pasedObject" but it can't because "AnyObject?" doesn't have that the member 0
do {
guard let pasedObject: AnyObject? = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0) ) else {
print("Failure")
return
}
print("Here is teh JSON String: \(pasedObject.0!)")
}
catch let error {
print("Bad Json path \(error)")
}
//This doesn't allow "AnyObject" to be subscripted.
do {
guard let pasedObject: AnyObject? = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0) ) else {
print("Failure")
return
}
print("Here is teh JSON String: \(pasedObject[0]!)")
}
catch let error {
print("Bad Json path \(error)")
}
//This will not work becaus it says "Any Object" doesn't have a member 1.
do {
guard let pasedObject: AnyObject? = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0) ) else {
print("Failure")
return
}
var locatedItem = pasedObject.1
print("Here is teh JSON String: \(pasedObject!)")
}
catch let error {
print("Bad Json path \(error)")
}
//This does not work because you can't call the value of a non-function this way!
do {
guard let pasedObject: AnyObject? = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0) ) else {
print("Failure")
return
}
print("Here is teh JSON String: \(pasedObject(0)!)")
}
catch let error {
print("Bad Json path \(error)")
}
//This didn't work it seemed to just pass over it and not print anything... This is because it runs into a "fatal error" while unwrapping the optional. This is because (1) the api has an inappropriate key. (2) the try-catch leads to a crash because it fails instead of not failing!
let webApi = NSURL(fileURLWithPath: "api.openweathermap.org/data/2.5/weather?q=London")
let testButton = NSData(contentsOfURL: webApi)
do {
guard let stringifyButton: AnyObject? = try! NSJSONSerialization.JSONObjectWithData(testButton!, options: NSJSONReadingOptions(rawValue: 0) ) else {
print("Failure Number Two")
return
}
print("Happy Path Result: \(stringifyButton)")
}
catch let error {
print("Bad JSON path: \(error)")
}
//Trying to parse strings didn't go well, it claims that I have an invalid character in position 1.
let StringJSON = "[MY, NAME, IS, Robert]"
let dataString = StringJSON.dataUsingEncoding(NSUTF8StringEncoding)!
do {
guard let parsedObject: AnyObject? = try NSJSONSerialization.JSONObjectWithData(dataString, options: NSJSONReadingOptions(rawValue: 0) ) else {
print("Failure")
return
}
print("Here is teh JSON String: \(parsedObject!)")
}
catch let error {
print("Bad Json path \(error)")
}
//Single qoutes didn't fix it either
let StringJSON = "['MY', 'NAME', 'IS', 'Robert']"
let dataString = StringJSON.dataUsingEncoding(NSUTF8StringEncoding)!
do {
guard let parsedObject: AnyObject? = try NSJSONSerialization.JSONObjectWithData(dataString, options: NSJSONReadingOptions(rawValue: 0) ) else {
print("Failure")
return
}
print("Here is teh JSON String: \(parsedObject!)")
}
catch let error {
print("Bad Json path \(error)")
}
//This code tries using NSString to parse the JSON string and it doesn't work!
let StringJSON = "['MY', 'NAME', 'IS', 'Robert']"
let dataStringOne = NSString(StringJSON.lowercaseString)
let dataString = StringJSON.dataUsingEncoding(NSUTF8StringEncoding)!
do {
guard let parsedObject: AnyObject? = try NSJSONSerialization.JSONObjectWithData(dataStringOne, options: NSJSONReadingOptions(rawValue: 0) ) else {
print("Failure")
return
}
print("Here is teh JSON String: \(parsedObject!)")
}
catch let error {
print("Bad Json path \(error)")
}
//This code doesn't work because it detected the wrong type of value in their and stopped it.
let NumberJSONError = "[0,6,7,13,69,100,String]"
let dataError = NumberJSONError.dataUsingEncoding(NSUTF8StringEncoding)!
do {
guard let pasedObject: AnyObject? = try NSJSONSerialization.JSONObjectWithData(dataError, options: NSJSONReadingOptions(rawValue: 0) ) else {
print("Failure")
return
}
print("Here is teh JSON String: \(pasedObject!)")
}
catch let error {
print("Bad Json path \(error)")
}
////////////////////////////////////////////////////
//Nasty Path code for Stringify
/////////////////////////////////////////////////////
// This has issues without the key values being surrrounded in qoutes, because of this the keys cannot be called/converted to a string and give us an error in the code!
let jsonDuoObject: [AnyObject] = [
[position: "Teacher", "ageRange": "25-65"],
[position: "Student", "ageRange": "5-24"],
]
func JSONStringifyDuo(value: AnyObject,prettyPrinted:Bool = false) -> String{
let options = prettyPrinted ? NSJSONWritingOptions.PrettyPrinted : NSJSONWritingOptions(rawValue: 0)
if NSJSONSerialization.isValidJSONObject(value) {
do{
let data = try NSJSONSerialization.dataWithJSONObject(value, options: options)
if let string = NSString(data: data, encoding: NSUTF8StringEncoding) {
return string as String
}
}catch {
print("error")
}
}
return ""
}
//Without the parameter, it cannot print and will not allow the code to compile.
let jsonDuoObjectTest = JSONStringifyDuo()
print(jsonString)
//This uses pretty printed which will pring the same info as the one above but prints it out so it is easier to show.
//However, by changing the value to false we DID NOT change the pretty printed option. If you call it, it willStill print it!
let jsonStringPrettyDuo = JSONStringifyDuo(jsonObject, prettyPrinted: false)
print(jsonStringPretty)
*/
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}