Class: Takagi::Serialization::JsonSerializer

Inherits:
Base
  • Object
show all
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.

Examples:

Encoding

serializer = JsonSerializer.new
bytes = serializer.encode({ temp: 25 })  # => "{\"temp\":25}"

Decoding

data = serializer.decode("{\"temp\":25}")  # => { "temp" => 25 }

Instance Method Summary collapse

Methods inherited from Base

#name

Instance Method Details

#binary?Boolean

JSON is text-based, not binary

Returns:

  • (Boolean)

    false



91
92
93
# File 'lib/takagi/serialization/json_serializer.rb', line 91

def binary?
  false
end

#content_format_codeInteger

CoAP content-format code for JSON

Returns:

  • (Integer)

    50 (RFC 7252 §12.3)



84
85
86
# File 'lib/takagi/serialization/json_serializer.rb', line 84

def content_format_code
  CoAP::Registries::ContentFormat::JSON
end

#content_typeString

MIME type for JSON

Returns:

  • (String)

    ‘application/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

Examples:

Object decoding

decode("{\"temp\":25}")  # => { "temp" => 25 }

Array decoding

decode("[1,2,3]")  # => [1, 2, 3]

Invalid JSON

decode("{invalid}")  # => nil

Parameters:

  • bytes (String)

    JSON bytes to decode

Returns:

  • (Object, nil)

    Decoded Ruby object (Hash, Array, String, etc.) or nil if invalid



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

Examples:

Hash encoding

encode({ temp: 25 })  # => "{\"temp\":25}"

Array encoding

encode([1, 2, 3])  # => "[1,2,3]"

String pass-through

encode("hello")  # => "hello"

Parameters:

  • data (Object)

    Ruby object to encode

Returns:

  • (String)

    JSON string as binary

Raises:



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.message}"
end