I have a Java HashMap that I have in JRuby, I am trying to convert it to JSON, but its not converting correctly, I think this example shows the problem:
$ irb [17:23:50]
irb(main):001:0> require 'java'
=> false
irb(main):003:0> require 'json'
=> true
irb(main):005:0> h = java.util.HashMap.new()
=> {}
irb(main):006:0> x = {}
=> {}
irb(main):007:0> JSON.parse JSON.dump x
=> {}
irb(main):008:0> JSON.parse JSON.dump h
JSON::ParserError: unexpected token at '"{}"'
from json/ext/Parser.java:251:in `parse'
from /Users/kimptoc/.rvm/rubies/jruby-1.7.3/lib/ruby/1.9/json/common.rb:155:in `parse'
from (irb):9:in `evaluate'
from org/jruby/RubyKernel.java:1066:in `eval'
from org/jruby/RubyKernel.java:1409:in `loop'
from org/jruby/RubyKernel.java:1174:in `catch'
from org/jruby/RubyKernel.java:1174:in `catch'
from /Users/kimptoc/.rvm/rubies/jruby-1.7.3/bin/irb:13:in `(root)'
irb(main):010:0> JSON.dump h
=> "\"{}\""
Any ideas on how to handle this - do I need to turn the map into a Ruby map?
Thanks, Chris
Currently, it seems you're right and the json
gem doesn't support HashMap
, so the only way is indeed to convert to ruby:
> JSON.parse JSON.dump h.to_hash
=> {}
It may be worth opening a ticket.
I have the same problem, but the to_hash workaround doesn't work when the java object is nested, see gist.
I was able to get it working with the jrjackson gem, and moved to multi_json to avoid dependencies in a specific implementation.
I've opened an issue in JRuby at https://github.com/jruby/jruby/issues/1931
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With