问题描述
我们正在升级我们的网络应用程序以使用 Facebook 的 Graph API,它返回 JSON 响应.然而,除非我们别无选择,否则我们不想向 JSON 库添加依赖项.对于服务器端 http 请求,我们使用 Apache HttpComponents.
we are upgrading our web app to use Facebook's Graph API, which returns JSON responses. However we don't want to add dependecy to a JSON library unless we have no other choice. For server-side http requests we use Apache HttpComponents.
因此,我的问题是我可以用来处理 JSON 响应的 JDK 和/或 HttpComponents 中有哪些类(如果有)?欢迎使用代码片段:)
Thus, my question is what are the classes (if any) in the JDK and/or in HttpComponents that I can use to process JSON responses? Code snippets are welcome :)
推荐答案
不幸的是,原生 JSON 支持 在 Java 9 之后延迟.
Unfortunately, native JSON support was delayed past Java 9.
但为了体育精神,这里是使用 Nashorn 没有任何外部依赖的 JavaScript 引擎:
But for the sake of sportmanship here is plain Java 8 hacky solution using Nashorn JavaScript engine without any external dependency:
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 数组.
Since Java 8u60 JSON.parse
can be substituted with Java.asJSONCompatible
which does better handling of JSON arrays.
学分:
在java之间传递JSON的有效方式和 javascript
https://dzone.com/articles/mapping-complex-json-structures-with-jdk8-nashorn
这篇关于是否可以仅使用 JDK 或 HttpComponents 处理 JSON 响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!