0

Is it possible to pass objects created in Javascript to java?

for example I have a POJO called myPojo with propertys name and address

The object is created in Javascript:

var myPojo = new Packages.CreatePOJO();

myPojo.setName("Alpha");

Then I pass it to a java function

var replacer = new Packages.VelocityReplace(); replacer.replace("a template", myPojo);

The replacer class is this.

public class VelocityReplace { public static String replace(String templateStr, Object in) throws Exception { ... }

The exception generated is:

Wrapped java.lang.ClassCastException: org.mozilla.javascript.NativeObject cannot be cast to CreatePOJO

I am using Mirth Connect which is a real time interfacing engine that is providing & pushing the data to the myPojo object. It uses javascript for scripting, this is why I need to push the data from javascript to java.

2
  • Is your Java running in an applet on your page? Or is it on your web server? Commented Aug 13, 2014 at 17:42
  • It's on the server, it's not a web server but an interface server, but the data handoff is similar I guess. Commented Aug 13, 2014 at 17:45

1 Answer 1

2

Use JSON, probably. I'm assuming you don't want to pass functions as part of your object from JS to Java. Java JSON libraries include GSON, Jackson and others.

2
  • So basically use to toJSON() function within javascript on the java variable to convert it to JSON, then pass it to Java, then convert it back to the original object using fromJSON from within my called Java function? Commented Aug 13, 2014 at 17:53
  • This works. In javascript do this: var gson = new Packages.com.google.gson.Gson(); var JSONstr = gson.toJson(myPojo); In java do this: Gson gson = new Gson(); POJO myPOJO = gson.fromJson(in, POJO.class); Commented Aug 13, 2014 at 18:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.