-
Notifications
You must be signed in to change notification settings - Fork 51
Description
Reading the docs for algolia, I noticed that you encourage at least Swift and C# users to load JSON data as dynamic values (e.g. Dictionary
and JObject
). Since this repo is about awesomeness, I thought you might be able to benefit from quicktype.
quicktype can infer types from JSON data and provide types and marshaling code in a variety of languages. For example, here's how to quicktype your airports.json
sample dataset:
$ npm install -g quicktype
$ quicktype -o Airports.swift \
https://raw.githubusercontent.com/algolia/datasets/master/airports/airports.json
This is the generated code:
typealias Airports = [Airport]
struct Airport: Codable {
let name, city, country, iataCode: String
let geoloc: Geoloc
let linksCount: Int
let objectID: String
enum CodingKeys: String, CodingKey {
case name, city, country
case iataCode = "iata_code"
case geoloc = "_geoloc"
case linksCount = "links_count"
case objectID
}
}
struct Geoloc: Codable {
let lat, lng: Double
}
extension Array where Element == Airports.Element {
init(data: Data) throws {
self = try JSONDecoder().decode(Airports.self, from: data)
}
init(_ json: String, using encoding: String.Encoding = .utf8) throws {
guard let data = json.data(using: encoding) else {
throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
}
try self.init(data: data)
}
func jsonData() throws -> Data {
return try JSONEncoder().encode(self)
}
func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
return String(data: try self.jsonData(), encoding: encoding)
}
}
Then you can easily go from JSON with Airports(jsonString)
and to JSON with airports.jsonString()
. With native support for Codable
in the algolia Swift SDK, you could make using algolia even nicer and more strongly typed without the need for the user to marshal strings or dynamic values.
quicktype would allow your C#, Swift, Objective-C, Java, Go, C++, etc. users use algolia type-safely with little effort. Not sure if this is useful in general, but I thought I'd draw your attention to this capability just in case!