Class: Rbdantic::Serialization::JsonSerializer
- Inherits:
-
Object
- Object
- Rbdantic::Serialization::JsonSerializer
- Defined in:
- lib/rbdantic/serialization/json_serializer.rb
Overview
JSON serialization and deserialization
Class Method Summary collapse
-
.dump(model, indent: nil, **options) ⇒ String
Serialize model to JSON string.
-
.load(json_string, model_class) ⇒ BaseModel
Parse JSON string into model.
-
.parse(json_string, model_class) ⇒ BaseModel?
Parse JSON string safely, returns nil on error.
-
.parse!(json_string, model_class) ⇒ BaseModel
Parse JSON string into model (raises on error).
Class Method Details
.dump(model, indent: nil, **options) ⇒ String
Serialize model to 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, **) data = Dumper.dump(model, mode: :json, **) 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
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
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)
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 |