如何使用 Jackson 解析 http servlet 中的 json



我使用 YUI 将 json 从页面发送到服务器以及如何从 servlet 中的 json 获取数据。我使用杰克逊库 2.4。谢谢!!!

var user = {
                   userName:   username,
                   password:   password,
                   customerId: customerId
                  };
           new Y.IO().send("http://localhost:7778/MyController", {
                method: 'POST',
                data: user
            });

实际上,当您提出这样的请求时

<html>
<body>
<script src="http://yui.yahooapis.com/3.14.1/build/yui/yui-min.js"></script>
<script>
var user = {
        userName:   'x1',
        password:   'y2',
        customerId: 'z3'
       };
YUI().use('io-form', function (Y) {
    new Y.IO().send("http://localhost:8080/web/MyController", {
        method: 'POST',
        data: user
    });
});
</script>
</body>
</html>

您不会将 JSON 对象发送到 servlet。相反,您正在创建一个 http 请求,其中 javascript 对象的每个属性(以 JSON 格式表示)都作为 http POST 属性发送,因此您可以像这样检索这些值

package mine;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Servlet implementation class MyController
 */
@WebServlet("/MyController")
public class MyController extends HttpServlet {
    private static final long serialVersionUID = 1L;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MyController() {
        super();
        // TODO Auto-generated constructor stub
    }
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Map<String, String[]> map = request.getParameterMap();
        for(Entry<String,String[]> entry:map.entrySet()){
            System.out.println(entry.getKey());
            System.out.println(entry.getValue()[0]);
        }
    }
}

这反过来打印了这个

userName
x1
password
y2
customerId
z3

因此,您不需要 Jackson 来解析您从页面检索到的数据。

最新更新