Method: JSONMapper::ClassMethods#parse_json

Defined in:
lib/json_mapper.rb

#parse_json(json) ⇒ Object



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/json_mapper.rb', line 79

def parse_json(json)

  # Set the JSON data for this instance
  self.json_data = json
  # @json_data[to_s] = json
  
  # Create a new instance of ourselves
  instance = new

  # Instantiate all AttributeList instances
  attributes.each do |attribute|
    if attribute.is_a?(AttributeList)
      instance.send("#{attribute.name}=", attribute.dup)
    end
  end

  # Traverse all defined attributes and assign data from the
  # JSON data structure
  attributes.each do |attribute|
    if is_mapped?(attribute, json)
      value = mapping_value(attribute, json)
      if attribute.is_a?(AttributeList)
        value = [ value ] unless value.is_a?(Array)
        value.each do |v|

          list_attribute = build_attribute(attribute.name, attribute.type, attribute.options)
          list_attribute_value = list_attribute.typecast(v)

          # Some times typecasting a value for a list will produce another list, in the case of
          # for instance DelimitedString. If this is the case, we concat that array to the list.
          # Otherwise, we just append the value.
          if list_attribute_value.is_a?(Array)
            instance.send("#{attribute.name}").concat(list_attribute_value)
          else
            instance.send("#{attribute.name}") << list_attribute_value
          end

        end
      else
        instance.send("#{attribute.name}=".to_sym, attribute.typecast(value))
      end
    end
  end

  instance

end