annotation Athena::Serializer::Annotations::Name

Overview

Defines the key to use during (de)serialization. If not provided, the name of the property is used. Also allows defining aliases that can be used for that property when deserializing.

Fields

Example

class Example
  include ASR::Serializable

  def initialize; end

  @[ASRA::Name(serialize: "myAddress")]
  property my_home_address : String = "123 Fake Street"

  @[ASRA::Name(deserialize: "some_key", serialize: "a_value")]
  property both_names : String = "str"

  @[ASRA::Name(key: "same")]
  property same_in_both_directions : String = "same for both"

  @[ASRA::Name(aliases: ["val", "value", "some_value"])]
  property some_value : String = "some_val"
end

ASR.serializer.serialize Example.new, :json # => {"myAddress":"123 Fake Street","a_value":"str","same":"same for both","some_value":"some_val"}

obj = ASR.serializer.deserialize Example, %({"my_home_address":"555 Mason Ave","some_key":"deserialized from diff key","same":"same again","value":"some_other_val"}), :json

obj.my_home_address         # => "555 Mason Ave"
obj.both_names              # => "deserialized from diff key"
obj.same_in_both_directions # => "same again"
obj.some_value              # => "some_other_val"

Naming Strategies

By default the keys in the serialized data match exactly to the name of the property. Naming strategies allow changing this behavior for all properties within the type. The serialized name can still be overridden on a per-property basis via using the ASRA::Name annotation with the serialize, deserialize or key field. The strategy will be applied on serialization, deserialization or both, depending on whether serialization_strategy, deserialization_strategy or strategy is used.

The available naming strategies include:

@[ASRA::Name(strategy: :camelcase)]
class User
  include ASR::Serializable

  def initialize; end

  property id : Int32 = 1
  property first_name : String = "Jon"
  property last_name : String = "Snow"
end

ASR.serializer.serialize User.new, :json # => {"id":1,"firstName":"Jon","lastName":"Snow"}

Defined in:

annotations.cr