I need to be able to read a JSON string from a file and parse it.
I want to know if the string is a "well formed" JSON. If so, I need to be able to read all the name value pairs.
Is there a JSON library that comes bundled with Java itself?
I would prefer something that comes with the standard Java distribution instead of downloading another external library.
I am using JDK 1.6.
Try it approach without using external library
http://blog.julienviet.com/2011/12/26/json-to-java-with-jdk6/
EDITED
GitHub is more reliable source of the code from specified link. https://gist.github.com/vietj/1521692
The key is to use javascript to parse, it can be invoked with:
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);
}
}
}
Javascript part, json2java.js:
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);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With