Skip to content

Instantly share code, notes, and snippets.

@carlossg carlossg/jruby-json.rb
Last active Aug 29, 2015

Embed
What would you like to do?
JRuby json conversion
# test conversion of Java objects to json in JRuby
# jrjackson is the only gem doing it right, the others quote the result
# the trick for the other ones is to convert maps and lists to ruby hashes and arrays before
array = java.util.ArrayList.new().to_array
list = java.util.ArrayList.new()
map = java.util.HashMap.new()
nested = { :list => list }
require 'jrjackson'
puts "*** jrjackson"
puts "Array: " + JrJackson::Json.dump([])
puts "Java Array: " + JrJackson::Json.dump(array)
puts "Java List to_a: " + JrJackson::Json.dump(list.to_a)
puts "Java List: " + JrJackson::Json.dump(list)
puts "Hash " + JrJackson::Json.dump({})
puts "Java Map: " + JrJackson::Json.dump(map)
puts "Java Map to_hash: " + JrJackson::Json.dump(map.to_hash)
puts "Nested list: " + JrJackson::Json.dump(nested)
puts "Nested list to_hash: " + JrJackson::Json.dump(nested.to_hash)
require 'gson'
puts "\n*** Gson"
puts "Array: " + Gson::Encoder.new.encode([])
puts "Java Array: " + Gson::Encoder.new.encode(array)
puts "Java List to_a: " + Gson::Encoder.new.encode(list.to_a)
puts "Java List: " + Gson::Encoder.new.encode(list)
puts "Hash " + Gson::Encoder.new.encode({})
puts "Java Map: " + Gson::Encoder.new.encode(map)
puts "Java Map to_hash: " + Gson::Encoder.new.encode(map.to_hash)
puts "Nested list: " + Gson::Encoder.new.encode(nested)
puts "Nested list to_hash: " + Gson::Encoder.new.encode(nested.to_hash)
require 'json'
puts "\n*** json"
puts "Array: " + JSON.dump([])
puts "Java Array: " + JSON.dump(array)
puts "Java List to_a: " + JSON.dump(list.to_a)
puts "Java List: " + JSON.dump(list)
puts "Hash " + JSON.dump({})
puts "Java Map: " + JSON.dump(map)
puts "Java Map to_hash: " + JSON.dump(map.to_hash)
puts "Nested list: " + JSON.dump(nested)
puts "Nested list to_hash: " + JSON.dump(nested.to_hash)
$ rvm jruby-1.7.14 do ruby json.rb
*** jrjackson
Array: []
Java Array: [Ljava.lang.Object;@21bcffb5
Java List to_a: []
Java List: []
Hash {}
Java Map: {}
Java Map to_hash: {}
Nested list: {"list":[]}
Nested list to_hash: {"list":[]}
*** Gson
Array: []
Java Array: "[Ljava.lang.Object;@21bcffb5"
Java List to_a: []
Java List: "[]"
Hash {}
Java Map: "{}"
Java Map to_hash: {}
Nested list: {"list":"[]"}
Nested list to_hash: {"list":"[]"}
*** json
Array: []
Java Array: "[Ljava.lang.Object;@21bcffb5"
Java List to_a: []
Java List: "[]"
Hash {}
Java Map: "{}"
Java Map to_hash: {}
Nested list: {"list":"[]"}
Nested list to_hash: {"list":"[]"}
@mrkaspa

This comment has been minimized.

Copy link

mrkaspa commented Oct 25, 2014

Is this problem only for dumping the string or there is another problem?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.