Last active
September 2, 2017 16:33
-
-
Save RockfordWei/7ad781656bd6ae576945cd5993240c67 to your computer and use it in GitHub Desktop.
Swift 4.0 JSON Usage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
public struct Person: Codable, Equatable { | |
public var name = "" | |
public var age = 0 | |
public static func == (lhs: Person, rhs: Person) -> Bool { | |
return lhs.name == rhs.name && lhs.age == rhs.age | |
} | |
} | |
public extension Data { | |
public func stringValue() -> String { | |
return self.withUnsafeBytes { (p: UnsafePointer<CChar>) -> String in | |
return String(cString: p) | |
} | |
} | |
} | |
let rocky = Person(name: "rocky", age: 24) | |
do { | |
let json = JSONEncoder() | |
let data = try json.encode(rocky) | |
let str = data.stringValue() | |
print(str) | |
let dec = JSONDecoder() | |
let person = try dec.decode(Person.self, from: data) | |
print(person) | |
print( person == rocky) | |
} catch { | |
print(error.localizedDescription) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment