1

Possible Duplicate:
Convert a JSON string to object in Java?

I'm working on a scripting implementation for a video game written in Java.

I'm interested in being able to define a javascript object such as:

var obj = ({
    x: 1,
    a: "meh",
    onEvent: function(info) {
       //do stuff
    }
});

and passing it through a determined pipeline into Java land. Currently, in Java I'm receiving the object as a sun.org.mozilla.javasript.internal.NativeObject which doesn't look very usable . Is there any way I can transfer the javascript into a Java object where I can access the data within? Specifically, without using GWT, as I'm not really working with web technologies.

EDIT FOR CLARITY: I'm not passing in a string of Javascript code to the Java function ala JSON. I'm using the javax.script package to evaluate entire scripts. Within the script engine there are bindings to Java objects with methods I'd like to pass in my javascript object as a parameter.

thanks in advance!

Community
  • 1
  • 1
JagWire
  • 269
  • 2
  • 16
  • you should read about [JSON in Java](http://www.json.org/java/). – Luiggi Mendoza May 25 '12 at 16:22
  • 1
    As far as I know, JSON doesn't allow functions, closures, etc... – JagWire May 25 '12 at 16:26
  • 1
    @JagWire you're right! Sorry, I didn't see that function there. – lbstr May 25 '12 at 17:26
  • 1
    How is this a duplicate of 'how to parse JSON in java?' The OP clearly stated he was trying to execute javascript from java, evidenced by his desire to execute instance methods on the object being passed in. Hell, he even clarified he was using java to parse javascript. – Pedantic Jun 28 '12 at 05:27
  • 1
    I concur with Pedantic, this is definitely not a question about using JSON in Java. – JagWire Jul 11 '12 at 14:55

1 Answers1

1

I haven't done much work with it, but the example from TFM seems like its not that difficult. Not sure what you've attempted already, but in any case:

public static void main(String[] args) throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");

    // JavaScript code in a String. This code defines a script object 'obj'
    // with one method called 'hello'.        
    String script = "var obj = new Object(); obj.hello = function(name) { print('Hello, ' + name); }";
    // evaluate script
    engine.eval(script);

    // javax.script.Invocable is an optional interface.
    // Check whether your script engine implements or not!
    // Note that the JavaScript engine implements Invocable interface.
    Invocable inv = (Invocable) engine;

    // get script object on which we want to call the method
    Object obj = engine.get("obj");    // <---- THIS IS A JAVA.LANG.OBJECT

    // invoke the method named "hello" on the script object "obj"
    inv.invokeMethod(obj, "hello", "Script Method !!" );
}
Pedantic
  • 5,032
  • 2
  • 24
  • 37