Re: JSON.stringify on Java object
Viktor Gamov
viktor.gamov at gmail.com
Mon Sep 16 19:45:40 PDT 2013
Hi Jim,
I thought so.
I have utility method like this (basically use jackson from js script):
@Test
public void convertToJson() throws ScriptException, NoSuchMethodException, FileNotFoundException {
Person person = new Person();
person.setFirstName("Vik");
person.setLastName("Gamov");
person.setSsn("111-11-11");
URL url = this.getClass().getClassLoader().getResource("javascript/json.js");
FileReader fileReader = new FileReader(new File(url.getFile()));
engine.eval(fileReader);
Invocable invocable = (Invocable) engine;
Object x = invocable.invokeMethod(engine.eval("json"), "toJson", person);
System.out.println(x);
}
json.js
var json = {};
var MAPPER = new com.fasterxml.jackson.databind.ObjectMapper();
json.toJson = function(object) {
return MAPPER.writeValueAsString(object);
};
json.roundtripJson = function(object) {
return JSON.parse(json.toJson(object));
};
Thanks
--
With Best Regards,
Vik Gamov
On September 16, 2013 at 9:27:09 PM, Jim Laskey (Oracle) (james.laskey at oracle.com) wrote:
Viktor,
We will not likely support stringify of Java Objects. It's hard to justify doing stringify without parse and then getting into the whole serialization security nightmare that plagued Rhino. If you RFE this feature it would be very restricted.
I'm not sure if you can accomplish the same effect with stringify replacer parameter https://developer.mozilla.org/en-US/docs/Using_native_JSON . Otherwise you'll have to implement your own utility.
Cheers,
-- Jim
On 2013-09-16, at 10:14 PM, Viktor Gamov <viktor.gamov at gmail.com> wrote:
> Hello Nashorn team,
>
> I have a question regarding conversion java object to json using JSON.stringify. Is it possible?
> Here is my test method
>
> @Test
> public void convertToJson() throws ScriptException, NoSuchMethodException {
> Person person = new Person();
> person.setFirstName("Vik");
> person.setLastName("Gamov");
> person.setSsn("111-11-11");
> Invocable invocable = (Invocable) engine;
> Object x = invocable.invokeMethod(engine.eval("JSON"), "stringify", person);
> System.out.println(x);
> }
>
> Prints null. Please advise.
>
> Thanks
>
> --
> With Best Regards,
> Vik Gamov
More information about the nashorn-dev
mailing list