Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert HTTP Request Body into JSON Object in Java

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

like image 389
empire29 Avatar asked Aug 16 '11 21:08

empire29


2 Answers

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;
}

With example usage:

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"], ...}
}
like image 81
maerics Avatar answered Oct 07 '22 01:10

maerics


Jackson is also a good option - its used extensively in Spring. Here is the tutorial: http://wiki.fasterxml.com/JacksonInFiveMinutes

like image 31
atrain Avatar answered Oct 07 '22 00:10

atrain