Module: javajava::util::Map
- Defined in:
- lib/jactive_support/core_ext/to_java_map.rb,
lib/jactive_support/json/encoders/map.rb,
lib/jactive_support/java_ext/map.rb
Overview
:nodoc:
Instance Method Summary collapse
-
#as_json(options = nil) ⇒ Object
:nodoc:.
- #to_java_map ⇒ Object
-
#to_json(options = {}) ⇒ Object
Returns a JSON string representing the hash.
Methods included from JactiveSupport::JavaExtensions::Map::Hash
#[], #[]=, #contains_key?, #contains_value?, #delete, #delete_if, #dup, #each, #each_key, #each_pair, #each_value, #fetch, included, #index, #invert, #keys, #length, #merge, #merge!, #reject, #reject!, #replace, #to_hash, #values_at
Instance Method Details
#as_json(options = nil) ⇒ Object
:nodoc:
42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/jactive_support/json/encoders/map.rb', line 42 def as_json( = nil) #:nodoc: if if attrs = [:except] except(*Array.wrap(attrs)) elsif attrs = [:only] slice(*Array.wrap(attrs)) else self end else self end end |
#to_java_map ⇒ Object
8 9 10 |
# File 'lib/jactive_support/core_ext/to_java_map.rb', line 8 def to_java_map self end |
#to_json(options = {}) ⇒ Object
Returns a JSON string representing the hash.
Without any options
, the returned JSON string will include all the hash keys. For example:
{ :name => "Konata Izumi", 'age' => 16, 1 => 2 }.to_json
# => {"name": "Konata Izumi", 1: 2, "age": 16}
The keys in the JSON string are unordered due to the nature of hashes.
The :only
and :except
options can be used to limit the attributes included, and will accept 1 or more hash keys to include/exclude.
{ :name => "Konata Izumi", 'age' => 16, 1 => 2 }.to_json(:only => [:name, 'age'])
# => {"name": "Konata Izumi", "age": 16}
{ :name => "Konata Izumi", 'age' => 16, 1 => 2 }.to_json(:except => 1)
# => {"name": "Konata Izumi", "age": 16}
The options
also filter down to any hash values. This is particularly useful for converting hashes containing ActiveRecord objects or any object that responds to options in their to_json
method. For example:
users = User.find(:all)
{ :users => users, :count => users.size }.to_json(:include => :posts)
would pass the :include => :posts
option to users
, allowing the posts association in the User model to be converted to JSON as well.
31 32 33 34 35 36 37 38 39 40 |
# File 'lib/jactive_support/json/encoders/map.rb', line 31 def to_json( = {}) #:nodoc: hash = as_json() return ActiveSupport::JSON.encode(hash, ) if hash != self result = '{' result << hash.map do |key, value| "#{ActiveSupport::JSON.encode(key.to_s)}:#{ActiveSupport::JSON.encode(value, )}" end * ',' result << '}' end |