如何从jsp接收和解析json数据?

时间:2016-10-10 15:40:42

标签: java json ajax jsp servlets

我从servlet那里发送一个json

User profileUser = userService.get(id);
request.setAttribute("profileUser", profileUser);
JSONObject json = new JSONObject();
try {
    json.put("profileUser", profileUser);
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
response.setContentType("application/json");
response.getWriter().write(json.toString());

在ajax调用的javascript中

$.ajax({
    cache : false,
    type : "GET",
    url : "UserServlet?id=" + userId,
    success : function(result) {
        alert(result.profileUser);
    }
});

警报的结果是给我Entity.user但是如果我想调用result.profileUser.uuid或该用户的属性返回我undefined。有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:1)

如果您要将json发送到Ajax客户端,那么您需要指定您即将收到json类型。像这样:

$.ajax({
    cache : false,
    type : "GET",
    dataType : "json",
    url : "UserServlet?id=" + userId,
    success : function(result) {
        alert(result.profileUser);
    }
});

这将导致您的success方法将结果参数计算为json对象。

答案 1 :(得分:0)

将您的Ajax更改为以下内容:

$.ajax({
    cache : false,
    type : "GET",
    url : "UserServlet?id=" + userId,
    success : function(profileUser) {
        alert(profileUser.uuid);
    }
});
相关问题