Skip to content

Instantly share code, notes, and snippets.

@vietj
Created December 26, 2011 17:34
Show Gist options
  • Save vietj/1521692 to your computer and use it in GitHub Desktop.
Save vietj/1521692 to your computer and use it in GitHub Desktop.
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