如何在 Java 中将 HTTP 请求正文转换为 JSON 对象
我正在尝试找到一个 Java lib/api,它允许我将 HTTP 请求 POST 正文的内容转换为 JSON 对象。
理想情况下,我想使用 Apache Sling 库(因为它们自然地暴露在我的容器中) )。
我找到的最接近的:org.apache.sling.commons.json.http
它将标头转换为 JSON。
HTTP Post 正文的格式为; key1=value1&key2=value2&..&keyn=valueN
所以我假设那里有东西,但我一直没能找到它。
如果某些东西尚不存在,我可能只需要使用自定义 JSONTokener
(org.apache.sling.commons.json.JSONTokener
) 来执行此操作。想法?
谢谢
I am trying find a Java lib/api that will allow me to turn the contents of a HTTP Request POST body into a JSON object.
Ideally I would like to use a Apache Sling library (as they are exposed in my container naturally).
The closest I've found it: org.apache.sling.commons.json.http
which converts the header to JSON.
HTTP Post bodies are in the format; key1=value1&key2=value2&..&keyn=valueN
so I assume there is something out there, but I havent been able to find it.
I may just have to use a custom JSONTokener
(org.apache.sling.commons.json.JSONTokener
) to do this if something doesn't already exist. Thoughts?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
假设您使用 HttpServlet 和像 json-simple 这样的 JSON 库,你可以这样做:
通过示例用法:
Assuming you're using an HttpServlet and a JSON library like json-simple you could do something like this:
With example usage:
Jackson 也是一个不错的选择 - 它在 Spring 中被广泛使用。这是教程:http://wiki.fasterxml.com/JacksonInFiveMinutes
Jackson is also a good option - its used extensively in Spring. Here is the tutorial: http://wiki.fasterxml.com/JacksonInFiveMinutes
我建议尝试 Apache Commons Beanutils。
I recommend trying Apache Commons Beanutils.
很抱歉将此作为自己的答案,但显然我的声誉不允许我简单地在答案中添加评论如何在Java中将HTTP请求体转换为JSON对象。
我还会迭代请求参数,但不使用任意 json 库,而是使用 sling 提供的 JSONObject。 http://sling.apache.org/ apidocs/sling6/org/apache/sling/commons/json/JSONObject.html
Sorry on making this an own answer but obviously my reputation doesn't allow me to simply add a comment to the answer How to convert HTTP Request Body into JSON Object in Java of maerics.
I would also iterate over the request params but instead of using an arbitrary json library use the JSONObject that is provided by sling. http://sling.apache.org/apidocs/sling6/org/apache/sling/commons/json/JSONObject.html
导入org.json.JSONObject;
import org.json.JSONObject;
使用Gson。有了这个,您可以创建带有私有变量的类,这些变量代表您想要的数据:例如。
Json 对象可以这样检索:
并且您的指令很简单。内容是您页面的内容,您可以使用 Asynctask 检索它。
Use Gson. With this you can create class with private variables which represent the data you want : for example.
Json Object could be retrieve like this :
And your instruction are simple. Content is the content of your Page, you can retrieve it with Asynctask.