1

我有简单的 Post 请求

POST /savings HTTP/1.1
Host: localhost:4567
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded

Body:
name=username&description=userdescription

我想知道如何将帖子正文转换name=username&description=userdescription为 Json,例如:

{
"name": "username", 
"description": "userdescription"
}

任何想法,我使用http://sparkjava.com,我需要处理内容类型的发布请求:application/x-www-form-urlencoded

post("/user", (request, response) -> {
// .. Convert request to User object
});
4

3 回答 3

1

您可以使用request.getParameter(String param)方法从 POST 请求中获取参数值。

我假设您使用的是 servlet,因此您可以在您的doPost()方法中执行以下操作:

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String name = request.getParameter("name");
    String description = request.getParameter("description");


        JSONObject json = new JSONObject();
        json.put("name", (name==null || name.isEmpty() ? "" : name));
        json.put("description", (description==null || description.isEmpty())? "" : description);

}

你会得到你需要的json:

{
  "name": "username", 
  "description": "userdescription"
}

所有学分都归于 HttpServletRequest 获取 JSON POST 数据

于 2015-07-10T13:25:32.027 回答
0

我个人使用 Google Gson 和请求对象来执行此操作。

值得注意的是,如果您使用 URL 参数,这将不起作用。

编辑:如果缺少任何参数,则 UserRequest 对象将为空,因为 gson 将无法构建该对象。

import java.io.InputStreamReader;
import com.google.gson.Gson;

import spark.Spark;

public class Handler
{
    private final Gson gson = new Gson();

    public Handler()
    {
    }

    public void init()
    {
        Spark.post("/user", (req, resp) -> {
            final UserRequest userRequest = gson.fromJson(new InputStreamReader(req.raw().getInputStream()), UserRequest.class);
            //do something with user
            return new Object();
        });
    }

    private static class UserRequest
    {
        private String name;
        private String description;

        public String getDescription()
        {
            return description;
        }

        public String getName()
        {
            return name;
        }
    }

    public static void main(final String[] args)
    {
        final Handler handler = new Handler();
        handler.init();
    }
}
于 2015-07-28T19:45:55.573 回答
0

我假设您从 servlet 中的 URL 获取参数,不是吗?

无论如何,作为 Regex 的练习,我会这样做:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class Any {


public static String queryStringToJasonParser(final String queryString){


    try {
            Pattern regex = Pattern.compile("(^|\\s+)name=(.*?)&description=(.*?)(\\s+|$)");
            Matcher regexMatcher = regex.matcher(queryString);

            if(regexMatcher.matches()){

                final String nameValue = regexMatcher.group(2);
                final String descriptionValue = regexMatcher.group(3);


                return "{\"name\": \""+nameValue+"\", \"description\": \""+descriptionValue+"\"}";


            }


    } catch (PatternSyntaxException ex) {
           //TODO: Handle it.
    }
    return "{\"name\": \"\", \"description\": \"\"}";

}



public static void main(String[] args){
    final String resultJason = Any.queryStringToJasonParser("name=wow1&description=wow2");
    System.out.println(resultJason);

    final String resultJason1 = Any.queryStringToJasonParser("name=&description=wow2");
    System.out.println(resultJason1);

}

}

添加任何所需的优化

问候

于 2015-07-10T13:23:55.753 回答