Deserialize json into proper classes. Better null handling for optional properties
This commit is contained in:
@@ -1,9 +1,73 @@
|
||||
require "http/client"
|
||||
require "io"
|
||||
require "json"
|
||||
|
||||
module Wince::Yelp
|
||||
extend self
|
||||
|
||||
class SearchResponse
|
||||
include JSON::Serializable
|
||||
property businesses : Array(Business)?
|
||||
property error : Error?
|
||||
end
|
||||
|
||||
class Error
|
||||
include JSON::Serializable
|
||||
property code : String
|
||||
property description : String
|
||||
end
|
||||
|
||||
class Business
|
||||
include JSON::Serializable
|
||||
property id : String
|
||||
property name : String
|
||||
property rating : Float32
|
||||
property distance : Float32
|
||||
end
|
||||
|
||||
class DetailsResponse
|
||||
include JSON::Serializable
|
||||
property error : Error?
|
||||
property name : String
|
||||
property price : String?
|
||||
property display_phone : String?
|
||||
property location : Location
|
||||
property coordinates : Coordinates
|
||||
property url : String
|
||||
property hours : Array(Hours)
|
||||
|
||||
def is_open
|
||||
hours[0].is_open_now
|
||||
end
|
||||
end
|
||||
|
||||
class Coordinates
|
||||
include JSON::Serializable
|
||||
property latitude : Float32
|
||||
property longitude : Float32
|
||||
end
|
||||
|
||||
class Location
|
||||
include JSON::Serializable
|
||||
property display_address : Array(String)
|
||||
end
|
||||
|
||||
class Hours
|
||||
include JSON::Serializable
|
||||
property open : Array(Open)
|
||||
property is_open_now : Bool
|
||||
end
|
||||
|
||||
class Open
|
||||
include JSON::Serializable
|
||||
property is_overnight : Bool
|
||||
@[JSON::Field(key: "start")]
|
||||
property open : String
|
||||
@[JSON::Field(key: "end")]
|
||||
property close : String
|
||||
property day : Int32
|
||||
end
|
||||
|
||||
@@token : String = {{ read_file("./api_key") }}
|
||||
|
||||
def search_businesses(search : String, location : String)
|
||||
@@ -21,6 +85,8 @@ module Wince::Yelp
|
||||
)
|
||||
headers = HTTP::Headers{ "Authorization" => "Bearer " + @@token }
|
||||
response = HTTP::Client.get(uri, headers)
|
||||
|
||||
{response.status_code, SearchResponse.from_json(response.body)}
|
||||
end
|
||||
|
||||
def get_business_info(id : String)
|
||||
@@ -32,6 +98,8 @@ module Wince::Yelp
|
||||
)
|
||||
headers = HTTP::Headers{ "Authorization" => "Bearer " + @@token }
|
||||
response = HTTP::Client.get(uri, headers)
|
||||
|
||||
{response.status_code, DetailsResponse.from_json(response.body)}
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user