Skip to content

Instantly share code, notes, and snippets.

@kmkrn
Last active December 30, 2017 00:51
Show Gist options
  • Save kmkrn/e6c40d34cae52001423f42e66d2a843b to your computer and use it in GitHub Desktop.
Save kmkrn/e6c40d34cae52001423f42e66d2a843b to your computer and use it in GitHub Desktop.
import Foundation
import RealmSwift
class JSONSerializer {
func serialize(input sourceName: String) {
let path = Bundle.main.path(forResource: sourceName, ofType: nil)
let url = URL(fileURLWithPath: path!)
let jsonDecoder = JSONDecoder()
do {
let data = try Data(contentsOf: url)
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
guard json is [AnyObject] else {
assert(false, "failed to parse")
return
}
do {
switch sourceName {
case "Cats":
let cats = try jsonDecoder.decode([Cat].self, from: data)
let realm = try! Realm()
for cat in cats {
try! realm.write {
realm.add(cat)
}
}
default:
let catPeople = try jsonDecoder.decode([CatPerson].self, from: data)
let realm = try! Realm()
for catPerson in catPeople {
try! realm.write {
realm.add(catPerson)
}
}
}
} catch {
print("failed to convert data")
}
} catch let error {
print(error)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment