从Rest服务返回JSON响应?

时间:2018-05-25 06:14:36

标签: java rest web-services

我开发了一个RESTful Web服务,它有一个POST方法。

我需要返回json回复。我可以将post方法返回类型为void并在json正文中设置httpresponse字符串吗?

我是否需要通过将方法返回类型更改为String来返回JSON字符串?推荐哪一个?请指导我......

谢谢!

1 个答案:

答案 0 :(得分:0)

是的,您可以将doPost的返回类型更改为void:

/**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
            String value = value; //JSON value you want to return
            StringBuilder out = new StringBuilder();
            out.append("{\"key\": \"" + value+ "\"}");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            response.getWriter().write(out.toString());
    }