java 是否可以仅使用 JDK 或 HttpComponents 处理 JSON 响应?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3970195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 04:12:13  来源:igfitidea点击:

is it possible to proccess JSON responses with the JDK or HttpComponents only?

jsonjavafacebook-graph-apihttpurlconnection

提问by Olivier

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.

我们正在升级我们的网络应用程序以使用 Facebook 的 Graph API,它返回 JSON 响应。然而,除非我们别无选择,否则我们不想向 JSON 库添加依赖项。对于服务器端 http 请求,我们使用 Apache 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 :)

因此,我的问题是 JDK 和/或 HttpComponents 中可用于处理 JSON 响应的类(如果有)是什么?欢迎使用代码片段:)

回答by BalusC

There are noneis the javax.scriptAPI as mentioned by @McDowell, but the JSON syntaxis pretty trivial. You could write a stackbased parser yourself which determines the JSON string char-by-char and converts JSON arrays []to a Object[]or List<Object>and JSON objects {}to a Map<String, Object>. It's a nice learning exercise. However, when you don't want to worry about long term robustness and maintenance, then I'd suggest to just pick one of the Java libraries listed at the bottom of this page. My personal favourite is Google Gson. It can nicelyconvert complex JSON structures into fullworthy and reuseable Javabeans.

是没有javax.scriptAPI由@McDowell提到,但JSON语法是相当琐碎。您可以自己编写一个基于堆栈的解析器,它逐个字符地确定 JSON 字符串,并将 JSON 数组转换[]为 a Object[]orList<Object>并将 JSON 对象转换{}为 a Map<String, Object>。这是一个很好的学习练习。但是,当您不想担心长期健壮性和维护时,我建议您只选择本页底部列出的 Java 库之一。我个人最喜欢的是Google Gson。它可以很好地将复杂的 JSON 结构转换为完全值得且可重用的 Javabean。

回答by McDowell

It is possible. Because JSON is valid JavaScript syntax, you can use the built-in JavaScript interpreter via the scripting APIto create and object graph, walk that (using the visitor pattern to push data into a Java object, for example).

有可能的。因为 JSON 是有效的 JavaScript 语法,所以您可以通过脚本 API使用内置的 JavaScript 解释器来创建和对象图,遍历它(例如,使用访问者模式将数据推送到 Java 对象中)。

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.

但是,您需要信任数据,否则您将面临代码注入攻击。对我来说,这不足以替代适当的 JSON 解析器。

回答by Vadzim

Unfortunately, native JSON support was delayed past Java 9.

不幸的是,原生 JSON 支持延迟到 Java 9 之后

But for the sake of sportmanship here is plain Java 8 hacky solution using NashornJavaScript engine without any external dependency:

但为了体育精神,这里是使用NashornJavaScript 引擎的纯 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]

Since Java 8u60JSON.parsecan be substituted with Java.asJSONCompatiblewhich does better handling of JSON arrays.

由于 Java 8u60JSON.parse可以替换为Java.asJSONCompatible它可以更好地处理 JSON 数组。

Credits:

学分:

Effective way to pass JSON between java and javascript

在java和javascript之间传递JSON的有效方法

https://dzone.com/articles/mapping-complex-json-structures-with-jdk8-nashorn

https://dzone.com/articles/mapping-complex-json-structures-with-jdk8-nashorn

回答by Christopher Martin

I think what you are looking for is the org.json package. You can get the source hereand 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.

我认为您正在寻找的是 org.json 包。您可以在此处获取源代码并在您的项目中简单地包含少量文件,它没有任何依赖项。这将允许您创建和解析 JSON。javadoc 做得很好,可以在这里找到。

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.

例如,对于使用 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");

Update: The source is also available at GitHub

更新:源代码也可以在GitHub 上找到