我们正在升级我们的网络应用程序以使用 Facebook 的 Graph API,它返回 JSON 响应。但是,除非我们别无选择,否则我们不想向 JSON 库添加依赖项。对于服务器端的 http 请求,我们使用 Apache HttpComponents。
因此,我的问题是我可以用来处理 JSON 响应的 JDK 和/或 HttpComponents 中的哪些类(如果有)?欢迎使用代码片段:)
我们正在升级我们的网络应用程序以使用 Facebook 的 Graph API,它返回 JSON 响应。但是,除非我们别无选择,否则我们不想向 JSON 库添加依赖项。对于服务器端的 http 请求,我们使用 Apache HttpComponents。
因此,我的问题是我可以用来处理 JSON 响应的 JDK 和/或 HttpComponents 中的哪些类(如果有)?欢迎使用代码片段:)
不幸的是,原生 JSON 支持延迟到 Java 9 之后。
但是为了体育精神,这里是使用Nashorn JavaScript 引擎的普通 Java 8 hacky 解决方案,没有任何外部依赖:
String json = "{\"foo\":1, \"bar\":\"baz\"}";
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
Object o = engine.eval(String.format("JSON.parse('%s')", json));
Map<String, String> map = (Map<String, String>) o;
System.out.println(Arrays.toString(map.entrySet().toArray()));
// [foo=1, bar=baz]
由于 Java 8u60 JSON.parse
可以替换为Java.asJSONCompatible
可以更好地处理 JSON 数组。
学分:
在 java 和 javascript 之间传递 JSON 的有效方法
https://dzone.com/articles/mapping-complex-json-structures-with-jdk8-nashorn
It is possible. Because JSON is valid JavaScript syntax, you can use the built-in JavaScript interpreter via the scripting API to create and object graph, walk that (using the visitor pattern to push data into a Java object, for example).
However, you need to trust the data or you leave yourself open to code injection attacks. To me, this would not be an adequate substitute for a proper JSON parser.
我认为您正在寻找的是 org.json 包。您可以在此处获取源代码,只需将少量文件包含在您的项目中,它没有任何依赖项。这将允许您创建和解析 JSON。javadocs 做得很好,可以在这里找到。
例如,为了使用 json,您可以使用标记器并将原始字符串转换为 JSONObject。然后您可以通过索引或键访问数组。您可以通过将嵌套数组获取为 JSONObject 或 JSONArray 来访问它们。
JSONTokener tokener = new JSONTokener(myJsonString);
JSONObject json = new JSONObject(tokener);
String error = json.get("error");
int errorCode = json.getInt("error_code");
JSONArray messages = json.getJsonArray("messages");
更新:源代码也可以在GitHub 上找到