Class: Typed::JSONSerializer

Inherits:
Serializer show all
Defined in:
lib/typed/json_serializer.rb

Constant Summary collapse

Input =
type_member { {fixed: String} }
Output =
type_member { {fixed: String} }

Constants inherited from Serializer

Serializer::DeserializeResult, Serializer::Params

Instance Attribute Summary

Attributes inherited from Serializer

#schema

Instance Method Summary collapse

Methods inherited from Serializer

#initialize

Constructor Details

This class inherits a constructor from Typed::Serializer

Instance Method Details

#deserialize(source) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
# File 'lib/typed/json_serializer.rb', line 11

def deserialize(source)
  parsed_json = JSON.parse(source)

  creation_params = schema.fields.each_with_object(T.let({}, Params)) do |field, hsh|
    hsh[field.name] = parsed_json[field.name.to_s]
  end

  deserialize_from_creation_params(creation_params)
rescue JSON::ParserError
  Failure.new(ParseError.new(format: :json))
end

#serialize(struct) ⇒ Object



24
25
26
27
28
# File 'lib/typed/json_serializer.rb', line 24

def serialize(struct)
  return Failure.new(SerializeError.new("'#{struct.class}' cannot be serialized to target type of '#{schema.target}'.")) if struct.class != schema.target

  Success.new(JSON.generate(serialize_from_struct(struct:, should_serialize_values: true)))
end