Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
JSON to Java
public class JSON2Java {
private static final ScriptEngine jsonParser;
static
{
try
{
String init = read(Tools.class.getResource("json2java.js"));
ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
engine.eval(init);
jsonParser = engine;
}
catch (Exception e)
{
// Unexpected
throw new AssertionError(e);
}
}
public static Object parseJSON(String json)
{
try
{
String eval = "new java.util.concurrent.atomic.AtomicReference(toJava((" + json + ")))";
AtomicReference ret = (AtomicReference)jsonParser.eval(eval);
return ret.get();
}
catch (ScriptException e)
{
throw new RuntimeException("Invalid json", e);
}
}
}
toJava = function(o) {
return o == null ? null : o.toJava();
};
Object.prototype.toJava = function() {
var m = new java.util.HashMap();
for (var key in this)
if (this.hasOwnProperty(key))
m.put(key, toJava(this[key]));
return m;
};
Array.prototype.toJava = function() {
var l = this.length;
var a = new java.lang.reflect.Array.newInstance(java.lang.Object, l);
for (var i = 0;i < l;i++)
a[i] = toJava(this[i]);
return a;
};
String.prototype.toJava = function() {
return new java.lang.String(this);
};
Boolean.prototype.toJava = function() {
return java.lang.Boolean.valueOf(this);
};
Number.prototype.toJava = function() {
return java.lang.Integer(this);
};
String eval = "new java.util.concurrent.atomic.AtomicReference(toJava((" + json + ")))";
AtomicReference ret = (AtomicReference)jsonParser.eval(eval);
return ret.get();
String init = read(Tools.class.getResource("json2java.js"));
ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
engine.eval(init);
jsonParser = engine;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment