如何在Java中将HTTP请求体转换为JSON对象 [英] How to convert HTTP Request Body into JSON Object in Java
问题描述
我正在尝试找到一个Java lib / api,它允许我将HTTP Request POST主体的内容转换为JSON对象。
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.
理想情况下我想要使用 Apache Sling 库(因为它们在我的容器中自然暴露)。
Ideally I would like to use a Apache Sling library (as they are exposed in my container naturally).
我发现它最接近: org.apache.sling.commons.json.http
将标题转换为JSON。
The closest I've found it: org.apache.sling.commons.json.http
which converts the header to JSON.
HTTP邮件正文格式; key1 = value1& key2 = value2& ..& keyn = valueN
所以我假设有一些东西,但我找不到它。
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.
我可能只需要使用自定义 JSONTokener
( org.apache.sling。 commons.json.JSONTokener
)如果某些内容尚不存在,则执行此操作。想法?
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?
谢谢
推荐答案
假设你正在使用< a href =http://download.oracle.com/javaee/6/api/javax/servlet/http/HttpServlet.html\"rel =noreferrer> HttpServlet 和一个像 json-simple 你可以这样做:
Assuming you're using an HttpServlet and a JSON library like json-simple you could do something like this:
public JSONObject requestParamsToJSON(ServletRequest req) {
JSONObject jsonObj = new JSONObject();
Map<String,String[]> params = req.getParameterMap();
for (Map.Entry<String,String[]> entry : params.entrySet()) {
String v[] = entry.getValue();
Object o = (v.length == 1) ? v[0] : v;
jsonObj.put(entry.getKey(), o);
}
return jsonObj;
}
使用示例:
public void doPost(HttpServletRequest req, HttpServletResponse res) {
JSONObject jsonObj = requestParamsToJSON(req);
// Now "jsonObj" is populated with the request parameters.
// e.g. {"key1":"value1", "key2":["value2a", "value2b"], ...}
}
这篇关于如何在Java中将HTTP请求体转换为JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!