如何在 Java 中将 HTTP 请求正文转换为 JSON 对象

发布于 2024-11-30 02:08:32 字数 518 浏览 1 评论 0原文

我正在尝试找到一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

魂ガ小子 2024-12-07 02:08:32

假设您使用 HttpServlet 和像 json-simple 这样的 JSON 库,你可以这样做:

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"], ...}
}

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"], ...}
}
请远离我 2024-12-07 02:08:32

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

潇烟暮雨 2024-12-07 02:08:32

我建议尝试 Apache Commons Beanutils

ServeltRequest request;

Map map = request.getParameterMap();
MyObject object = new MyObject();
BeanUtils.populate(object, map);
String json = object.toJSON() //using any JSON library

I recommend trying Apache Commons Beanutils.

ServeltRequest request;

Map map = request.getParameterMap();
MyObject object = new MyObject();
BeanUtils.populate(object, map);
String json = object.toJSON() //using any JSON library
小草泠泠 2024-12-07 02:08:32

很抱歉将此作为自己的答案,但显然我的声誉不允许我简单地在答案中添加评论如何在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

や莫失莫忘 2024-12-07 02:08:32

导入org.json.JSONObject;

 JSONObject json = new JSONObject(request.getParameterMap())

import org.json.JSONObject;

 JSONObject json = new JSONObject(request.getParameterMap())
电影里的梦 2024-12-07 02:08:32

使用Gson。有了这个,您可以创建带有私有变量的类,这些变量代表您想要的数据:例如。

meta:{
       name:"Example"
       firstname:"Example2"
     }
data:[
      {
        title:"ecaetra"
        description:"qwerty"
      }
      ...
     ]

Json 对象可以这样检索:

public class RetrieveData {

      private Meta meta;
      private List<Data> data;

      public Meta getMeta(){
            return meta;
      }

      public List<Data> getData(){
            return data;
      }
}

public class Meta {

      private String name;
      private String firstname;

      public String getName(){
            return name;
      }

      public String getFirstName(){
            return firstname;
      }

}

public class Data {

      private String title;
      private String description;

      public String getTitle(){
            return title;
      }

      public String getDescription(){
            return description;
      }

}

并且您的指令很简单。内容是您页面的内容,您可以使用 Asynctask 检索它。

 Object o = new Gson().fromJson(Content, RetrieveData.class);
 data = (RetrieveData)o;
 // Get Meta
    data.getName(); // Example
    data.getFirstName(); // Example2
 // Get Data
    data.get(0).getTitle(); // position 0 : ecaetra
    data.get(0).getDescription(); // position 0 : qwerty

Use Gson. With this you can create class with private variables which represent the data you want : for example.

meta:{
       name:"Example"
       firstname:"Example2"
     }
data:[
      {
        title:"ecaetra"
        description:"qwerty"
      }
      ...
     ]

Json Object could be retrieve like this :

public class RetrieveData {

      private Meta meta;
      private List<Data> data;

      public Meta getMeta(){
            return meta;
      }

      public List<Data> getData(){
            return data;
      }
}

public class Meta {

      private String name;
      private String firstname;

      public String getName(){
            return name;
      }

      public String getFirstName(){
            return firstname;
      }

}

public class Data {

      private String title;
      private String description;

      public String getTitle(){
            return title;
      }

      public String getDescription(){
            return description;
      }

}

And your instruction are simple. Content is the content of your Page, you can retrieve it with Asynctask.

 Object o = new Gson().fromJson(Content, RetrieveData.class);
 data = (RetrieveData)o;
 // Get Meta
    data.getName(); // Example
    data.getFirstName(); // Example2
 // Get Data
    data.get(0).getTitle(); // position 0 : ecaetra
    data.get(0).getDescription(); // position 0 : qwerty
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文