tags:

views:

160

answers:

1

I'm using JDK6the standard Scripting. I need to store and retrieve some JavaScript Objects that also contain Java Objects to JSON. I loaded the json2.js into the ScriptENgine and can use it fine without issue if the objects are all created in the Scrip Engine. The moment I try to use my own Java classes, I get some errors like "object does not support toJSON" errors.

I did not find much about JSON in Java Scripting / Rhino context.

Am I doing something totally wrong? What's the best way of achieving the requirement?

A: 

As far as I know, rhino does not contain a built-in JSON serialization capability.

The errors you're seeing are probably because json2.js uses the statement typeof value.toJSON to determine of the object in question implements its own serialization function. On JavaScript objects, failed property lookups return undefined. On Java objects, failed member lookups throw exceptions.

One approach to solving this problem would be to modify json2 such that as it traverses an object structure:

  1. it checks whether each value in question extends from the JavaScript base Object prototype or the Java Object base class, and
  2. applies different encoding logic for Java and JavaScript object instances.

I don't know if anyone has already tackled the problem of serializing an arbitrary Java object to JSON via reflection. If so, then this might be a good use of it.

Hope this helps!

jimbojw