Skip to content

Commit

Permalink
test json serializer
Browse files Browse the repository at this point in the history
  • Loading branch information
tanner0101 committed Jan 27, 2016
1 parent a863486 commit edffb94
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 10 deletions.
68 changes: 68 additions & 0 deletions Sources/JSONSerializer.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import Foundation

class JSONSerializer {

class func serialize(object: Any) -> String {

if let dict = object as? [String: Any] {
var s = "{"
var i = 0

for (key, val) in dict {
s += "\"\(key)\":\(self.serialize(val))"
if i != (dict.count - 1) {
s += ","
}
i += 1
}

return s + "}"
} else if let dict = object as? NSDictionary {
var s = "{"
var i = 0

for (key, val) in dict {
s += "\"\(key)\":\(self.serialize(val))"
if i != (dict.count - 1) {
s += ","
}
i += 1
}

return s + "}"
} else if let array = object as? [Any] {
var s = "["

for i in 0 ..< array.count {
s += self.serialize(array[i])

if i != (array.count - 1) {
s += ","
}
}

return s + "]"
} else if let array = object as? NSArray {
var s = "["

for i in 0 ..< array.count {
s += self.serialize(array[i])

if i != (array.count - 1) {
s += ","
}
}

return s + "]"
} else if let string = object as? String {
return "\"\(string)\""
} else if let number = object as? Int {
return "\(number)"
} else {
print(object)
print(Mirror(reflecting: object))
return ""
}

}
}
12 changes: 2 additions & 10 deletions Sources/Response.swift
Original file line number Diff line number Diff line change
Expand Up @@ -179,16 +179,8 @@ public class Response {
}

public convenience init(status: Status, json: Any) throws {
guard let jsonObject = json as? AnyObject else {
throw SerializationError.InvalidObject
}
guard NSJSONSerialization.isValidJSONObject(jsonObject) else {
throw SerializationError.InvalidObject
}

let json = try NSJSONSerialization.dataWithJSONObject(jsonObject, options: NSJSONWritingOptions.PrettyPrinted)
let data = Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>(json.bytes), count: json.length))

let string = JSONSerializer.serialize(json)
let data = [UInt8](string.utf8)
self.init(status: status, data: data, contentType: .Json)
}
}
Expand Down

0 comments on commit edffb94

Please sign in to comment.