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

时间:2014-02-15 10:42:05

标签: json jackson

我使用YUI从页面向服务器发送json,以及如何从servlet中的json获取数据。我使用jackson lib 2.4。感谢!!!

var user = {
                   userName:   username,
                   password:   password,
                   customerId: customerId
                  };

           new Y.IO().send("http://localhost:7778/MyController", {
                method: 'POST',
                data: user
            });

1 个答案:

答案 0 :(得分:0)

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

<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>

您没有向servlet发送JSON对象。相反,您正在创建一个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

所以你不需要杰克逊来解析你从你的页面检索的数据。