Class: Resto::Format::Json

Inherits:
Object
  • Object
show all
Extended by:
Resto::Format
Defined in:
lib/resto/format/json.rb

Overview

Note:

This class is only used internally by these classes/modules: Request::Base (see method Request::Header#formatter) uses this class to create a valid JSON request. Response::Base (see method Response::Base#read_body) uses this class to convert a JSON formatted String to a Hash.

Class Method Summary collapse

Methods included from Resto::Format

accept, content_type, decode, encode, extension, get

Class Method Details

.acceptString

The accept header when sending JSON data.

Example:

headers["accept"] = Resto::Format::Json.accept

Returns:

  • (String)

    “application/json, /



22
# File 'lib/resto/format/json.rb', line 22

def accept; 'application/json, */*'; end

.content_typeString

The content-type header when sending JSON data.

Example:

headers["content-type"] = Resto::Format::Json.content_type

Returns:

  • (String)

    “application/json”



30
# File 'lib/resto/format/json.rb', line 30

def content_type; 'application/json'; end

.decode(json, options = nil) ⇒ Array<Hash>

Converts a JSON formatted String to an Array of a Hashes.

Example:

Json.decode("{\"root\":{\"body\":\"I am a body\"}}")
  # => [{ 'root': { 'body': 'I am a body' } }]

Parameters:

  • json (String)
  • options (defaults to: nil)

    is not used.

Returns:

  • (Array<Hash>)

Raises:

  • (ArgumentError)


42
43
44
45
46
47
# File 'lib/resto/format/json.rb', line 42

def decode(json, options=nil)
  raise ArgumentError unless json.is_a?(String)

  result = Yajl::Parser.parse(json)
  result.is_a?(Array) ? result : [result].compact
end

.encode(hash, options = nil) ⇒ String

Converts a Hash to a JSON formatted String.

Example:

Json.encode({ root: { body: 'I am a body' } })
  # => "{\"root\":{\"body\":\"I am a body\"}}"

Parameters:

  • hash (Hash)
  • options (defaults to: nil)

    is not used.

Returns:

  • (String)

Raises:

  • (ArgumentError)


59
60
61
62
63
# File 'lib/resto/format/json.rb', line 59

def encode(hash, options = nil)
  raise ArgumentError unless hash.is_a?(Hash)

  Yajl::Encoder.encode(hash)
end

.extensionString

The extension name used (if required) as the URL suffix.

Example:

http://myhost.com:8085/bamboo/rest/api/latest/plan.json

Returns:

  • (String)

    “json”



71
# File 'lib/resto/format/json.rb', line 71

def extension; 'json'; end