与Java捆绑在一起的标准JSON解析器 [英] Standard JSON parser that comes bundled with Java
问题描述
我需要能够从文件中读取JSON字符串并解析它。
I need to be able to read a JSON string from a file and parse it.
我想知道字符串是否是格式良好的JSON。如果是这样,我需要能够读取所有名称值对。
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.
是否有与Java本身捆绑在一起的JSON库?
Is there a JSON library that comes bundled with Java itself?
我更喜欢标准Java发行版附带的东西,而不是下载另一个外部库。
I would prefer something that comes with the standard Java distribution instead of downloading another external library.
我使用的是JDK 1.6。
I am using JDK 1.6.
推荐答案
尝试使用方法而不使用外部库
http://blog.julienviet.com/2011 / 12/26 / json-to-java-with-jdk6 /
EDITED
GitHub是来自指定链接的更可靠的代码源。
https://gist.github.com/vietj/1521692
GitHub is more reliable source of the code from specified link. https://gist.github.com/vietj/1521692
关键是使用javascript进行解析,可以调用:
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 :
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);
};
这篇关于与Java捆绑在一起的标准JSON解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!