Class: Takagi::Serialization::JsonSerializer
- Defined in:
- lib/takagi/serialization/json_serializer.rb
Overview
JSON serializer (RFC 8259)
Handles application/json content-format (code 50). Encodes Ruby objects to JSON and decodes JSON to Ruby objects.
Instance Method Summary collapse
-
#binary? ⇒ Boolean
JSON is text-based, not binary.
-
#content_format_code ⇒ Integer
CoAP content-format code for JSON.
-
#content_type ⇒ String
MIME type for JSON.
-
#decode(bytes) ⇒ Object?
Decode JSON bytes to Ruby object.
-
#encode(data) ⇒ String
Encode Ruby object to JSON bytes.
Methods inherited from Base
Instance Method Details
#binary? ⇒ Boolean
JSON is text-based, not binary
91 92 93 |
# File 'lib/takagi/serialization/json_serializer.rb', line 91 def binary? false end |
#content_format_code ⇒ Integer
CoAP content-format code for JSON
84 85 86 |
# File 'lib/takagi/serialization/json_serializer.rb', line 84 def content_format_code CoAP::Registries::ContentFormat::JSON end |
#content_type ⇒ String
MIME type for JSON
77 78 79 |
# File 'lib/takagi/serialization/json_serializer.rb', line 77 def content_type 'application/json' end |
#decode(bytes) ⇒ Object?
Decode JSON bytes to Ruby object
66 67 68 69 70 71 72 |
# File 'lib/takagi/serialization/json_serializer.rb', line 66 def decode(bytes) return nil if bytes.nil? || bytes.empty? JSON.parse(bytes) rescue JSON::ParserError => e nil # Return nil for invalid JSON end |
#encode(data) ⇒ String
Encode Ruby object to JSON bytes
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/takagi/serialization/json_serializer.rb', line 33 def encode(data) return ''.b if data.nil? || data == '' result = case data when String # Already a string, assume it's valid data when Hash, Array # Structured data - convert to JSON JSON.generate(data) else # Other objects - try to_json data.to_json end result.b rescue StandardError => e raise EncodeError, "JSON encoding failed: #{e.}" end |