Module: EasyPost::InternalUtilities::Json

Defined in:
lib/easypost/utilities/json.rb

Class Method Summary collapse

Class Method Details

.convert_json_to_object(data, cls = EasyPost::Models::EasyPostObject) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/easypost/utilities/json.rb', line 4

def self.convert_json_to_object(data, cls = EasyPost::Models::EasyPostObject)
  data = JSON.parse(data) if data.is_a?(String) # Parse JSON to a Hash or Array if it's a string
  if data.is_a?(Array)
    # Deserialize array data into an array of objects
    data.map { |i| convert_json_to_object(i, cls) }
  elsif data.is_a?(Hash)
    # Deserialize hash data into a new object instance
    cls.new(data)
  else
    # data is neither a Hash nor Array (but somehow was parsed as JSON? This should never happen)
    data
  end
rescue JSON::ParserError
  data # Not JSON, return the original data (used mostly when dealing with final values like strings, booleans, etc.)
end

.http_response_is_json?(response) ⇒ Boolean

Returns:

  • (Boolean)


20
21
22
# File 'lib/easypost/utilities/json.rb', line 20

def self.http_response_is_json?(response)
  response['Content-Type'] ? response['Content-Type'].start_with?('application/json') : false
end