How to convert HTTP Request Body into JSON Object in Java

后端 未结 6 902
挽巷
挽巷 2020-12-10 04:45

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 li

6条回答
  •  庸人自扰
    2020-12-10 05:13

    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 params = req.getParameterMap();
      for (Map.Entry 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"], ...}
    }
    

提交回复
热议问题