Class: MotionPrime::JSON

Inherits:
Object
  • Object
show all
Defined in:
motion-prime/models/json.rb

Constant Summary collapse

PARAMETRIZE_CLASSES =
[Time, Date]

Class Method Summary collapse

Class Method Details

.generate(obj, parametrize = true) ⇒ String

Generates a string from data structure.

Parameters:

  • obj (String, Fixnum, Array, Hash, Nil)

    the object to serialize.

  • parametrize (Boolean) (defaults to: true)

    option to parametrize data before serialization.

Returns:

  • (String)

    the serialized data json.



27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'motion-prime/models/json.rb', line 27

def self.generate(obj, parametrize = true)
  if parametrize && obj.is_a?(Hash)
    obj.each do |key, value|
      obj[key] = value.to_s if PARAMETRIZE_CLASSES.include?(value.class)
    end
  end
  if parametrize && obj.is_a?(Array)
    obj.map! do |value|
      PARAMETRIZE_CLASSES.include?(value.class) ? value.to_s : value
    end
  end
  data = NSJSONSerialization.dataWithJSONObject(obj, options: 0, error: nil)
  data.to_str
end

.parse(str_data, &block) ⇒ Hash, ...

Parses a string or data object and converts it in data structure.

Parameters:

  • str_data (String, NSData)

    the string or data to convert.

Returns:

  • (Hash, Array, NilClass)

    the converted data structure, nil if the incoming string isn’t valid.

Raises:

  • (JsonParseError)

    If the parsing of the passed string/data isn’t valid.



12
13
14
15
16
17
18
19
20
# File 'motion-prime/models/json.rb', line 12

def self.parse(str_data, &block)
  return nil unless str_data
  data = str_data.respond_to?(:to_data) ? str_data.to_data : str_data
  opts = NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves | NSJSONReadingAllowFragments
  error = Pointer.new(:id)
  obj = NSJSONSerialization.JSONObjectWithData(data, options: opts, error: error)
  raise JsonParseError, error[0].description if error[0]
  obj
end