How to convert java map to json in jruby

I have a Java HashMap that I have in JRuby, I try to convert it to JSON, but it does not convert 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?

Thank you, Chris

+5
source share
2 answers

Currently, it seems that you are right, and the stone jsondoes not support HashMap, so the only way is to convert to ruby:

> JSON.parse JSON.dump h.to_hash
=> {}

It might be worth opening a ticket .

+4
source

I have the same problem, but the to_hash workaround does not work when the java object is nested, see gist .

jrjackson gem multi_json, .

JRuby https://github.com/jruby/jruby/issues/1931

+2

All Articles