-
-
Save wendal/2413967 to your computer and use it in GitHub Desktop.
JSON to Java (Use ScriptEngine in JDK6)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class JSON2Java { | |
private static final ScriptEngine jsonParser; | |
static { | |
try { | |
String init = read(JSON2Java.class.getResource("json2java.js")); | |
ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript"); | |
engine.eval(init); | |
jsonParser = engine; | |
} | |
catch (Exception e) { | |
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); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}; | |
//add More Type, by wendal | |
Date.prototype.toJava = function() { | |
return java.util.Date(this); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment