是否可以仅使用 JDK 或 HttpComponents 处理 JSON 响应?
我们正在升级我们的网络应用程序以使用 Facebook 的 Graph API,该 API 返回 JSON 响应。但是,除非我们别无选择,否则我们不想向 JSON 库添加依赖项。对于服务器端 http 请求,我们使用 Apache HttpComponents。
因此,我的问题是 JDK 和/或 HttpComponents 中可以用来处理 JSON 响应的类(如果有)是什么?欢迎使用代码片段:)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不幸的是,原生 JSON 支持在 Java 9 之后被延迟。
但为了体育精神,这里是使用 Nashorn 的普通 Java 8 hacky 解决方案 没有任何外部依赖的 JavaScript 引擎:
自 Java 8u60
JSON.parse
可以替换为Java.asJSONCompatible
可以更好地处理 JSON 数组。学分:
在java和java之间传递JSON的有效方法javascript
https://dzone.com/articles/映射复杂-json-结构-with-jdk8-nashorn
Unfortunately, native JSON support was delayed past Java 9.
But for the sake of sportmanship here is plain Java 8 hacky solution using Nashorn JavaScript engine without any external dependency:
Since Java 8u60
JSON.parse
can be substituted withJava.asJSONCompatible
which does better handling of JSON arrays.Credits:
Effective way to pass JSON between java and javascript
https://dzone.com/articles/mapping-complex-json-structures-with-jdk8-nashorn
这是可能的。由于 JSON 是有效的 JavaScript 语法,因此您可以通过 脚本 API 来创建对象图,执行该操作(例如,使用访问者模式将数据推送到 Java 对象中)。
但是,您需要信任这些数据,否则您将面临代码注入攻击。对我来说,这并不能充分替代合适的 JSON 解析器。
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。 javadoc 做得很好,可以找到 此处。
例如,为了使用 json,您可以使用标记器并将原始字符串转换为 JSONObject。然后您可以通过索引或键访问数组。您可以通过将嵌套数组作为 JSONObject 或 JSONArray 来访问它们。
更新:
源代码也可在 GitHub 获取
I think what you are looking for is the org.json package. You can get the source here and simply include the handful of files in your project, it doesn't have any dependencies. This will allows you do create and parse JSON. The javadocs are well done and can be found here.
As an example, for consuming json, you can use a tokener and convert the raw string to a JSONObject. Then you can access the arrays by index or by key. You can access nested arrays by getting them as a JSONObject or JSONArray.
Update:
The source is also available at GitHub