Parsing JSON via ScriptEngine in the JDK

I’m writing some REST WebServices that return JSON and wanted to ensure that my JSON was correctly formatted and parsable. Since the JDK ships with a JavaScript engine built into it now, I figured it would be simplest to just use that and avoid any external dependencies. Here’s my code:

ScriptEngine se = new ScriptEngineManager().getEngineByExtension("js");
se.eval("var obj = " + json + ";");

Pretty simple overall. The only tricky part is that you need to add the “var obj = ” and the semicolon on the end so that the JavaScript engine can evaluate it correctly.

One thought on “Parsing JSON via ScriptEngine in the JDK

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s