Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Java Map to json in jruby

Tags:

java

json

rvm

jruby

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

like image 561
Chris Kimpton Avatar asked Apr 23 '13 16:04

Chris Kimpton


2 Answers

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.

like image 200
Sébastien Le Callonnec Avatar answered Oct 11 '22 18:10

Sébastien Le Callonnec


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

like image 28
csanchez Avatar answered Oct 11 '22 18:10

csanchez