Class: Rbdantic::Serialization::JsonSerializer

Inherits:
Object
  • Object
show all
Defined in:
lib/rbdantic/serialization/json_serializer.rb

Overview

JSON serialization and deserialization

Class Method Summary collapse

Class Method Details

.dump(model, indent: nil, **options) ⇒ String

Serialize model to JSON string

Parameters:

  • model (BaseModel)

    the model instance

  • indent (Integer, nil) (defaults to: nil)

    JSON indentation

Returns:

  • (String)

    JSON string



13
14
15
16
17
18
19
20
21
# File 'lib/rbdantic/serialization/json_serializer.rb', line 13

def self.dump(model, indent: nil, **options)
  data = Dumper.dump(model, mode: :json, **options)

  if indent
    JSON.pretty_generate(data, indent: normalize_indent(indent))
  else
    JSON.generate(data)
  end
end

.load(json_string, model_class) ⇒ BaseModel

Parse JSON string into model

Parameters:

  • json_string (String)

    JSON data

  • model_class (Class)

    target model class

Returns:



27
28
29
30
# File 'lib/rbdantic/serialization/json_serializer.rb', line 27

def self.load(json_string, model_class)
  data = JSON.parse(json_string, symbolize_names: true)
  model_class.new(data)
end

.parse(json_string, model_class) ⇒ BaseModel?

Parse JSON string safely, returns nil on error

Parameters:

  • json_string (String)

    JSON data

  • model_class (Class)

    target model class

Returns:



44
45
46
47
48
49
50
# File 'lib/rbdantic/serialization/json_serializer.rb', line 44

def self.parse(json_string, model_class)
  begin
    load(json_string, model_class)
  rescue JSON::ParserError, ValidationError
    nil
  end
end

.parse!(json_string, model_class) ⇒ BaseModel

Parse JSON string into model (raises on error)

Parameters:

  • json_string (String)

    JSON data

  • model_class (Class)

    target model class

Returns:



36
37
38
# File 'lib/rbdantic/serialization/json_serializer.rb', line 36

def self.parse!(json_string, model_class)
  load(json_string, model_class)
end