让我解释一下目前的状态,然后我会提到这个问题。
在我的jsp页面中,我通过javascript中$getJSON
的{{1}}方法调用Struts 2 Action。
以下是代码:
jQuery
我想在我的Struts Action类中读取通过请求发送的json对象。 这是我的Action类:
var a = {"id":"ddsa","firstName":"dasda","lastName":"asaas","email":"dasdds"};
var b = {"id":"ddsa","firstName":"dasda","lastName":"asaas","email":"dasdds"};
var c = {"id":"ddsa","firstName":"dasda","lastName":"asaas","email":"dasdds"};
var users = [a,b,c];
$.getJSON
(
"createUser.action",
{
"users":users+""
},
function (data){
// alert(data.status);
if(data.status == "SUCCESS"){
location.reload();
}else{
alert("Creating User Failed");
}
}
);
我得到一个像这样的异常堆栈跟踪:
public class ProcessUser extends ActionSupport implements ServletRequestAware {
private HttpServletRequest request;
@Override
public void setServletRequest(HttpServletRequest servletRequest) {
// TODO Auto-generated method stub
this.request = servletRequest;
}
public String execute() {
String data = request.getParameter("users");
System.out.println("data is :"+data);
//data = "{\"users\":"+data+"}";
System.out.println("data is :"+data);
//data = "{\n \"users\": [\n {\n \"id\": \"ddsa\",\n \"firstName\": \"dasda\",\n \"lastName\": \"asaas\",\n \"email\": \"dasdds\"\n },\n {\n \"id\": \"ddsa\",\n \"firstName\": \"dasda\",\n \"lastName\": \"asaas\",\n \"email\": \"dasdds\"\n }\n ]\n}";
try {
JSONObject json = (JSONObject)new JSONParser().parse(data);
JSONArray jsonArray = (JSONArray)json.get("users");
JSONObject jsonObject = (JSONObject)jsonArray.get(0);
System.out.println("id:"+jsonObject.get("firstName"));
/*
System.out.println("name=" + json.get("users[id"));
System.out.println("width=" + json.get("users.firstName"));*/
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return SUCCESS;
}
你能帮我解决这个问题。我怎样才能读出那个json对象。
答案 0 :(得分:0)
尝试使用以下代码声明数组
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( input );
其中input是JSON字符串
答案 1 :(得分:0)
经过多次迭代后,我找到了问题的解决方案。
从JavaScript发送请求时,我必须使用JSON.stringify(data)
,即
var a = {"id":"ddsa","firstName":"dasda","lastName":"asaas","email":"dasdds"};
var b = {"id":"ddsa","firstName":"dasda","lastName":"asaas","email":"dasdds"};
var c = {"id":"ddsa","firstName":"dasda","lastName":"asaas","email":"dasdds"};
var users = [a,b,c];
$.getJSON
(
"createUser.action",
{
"users":JSON.stringify(users)
},
function (data){
// alert(data.status);
if(data.status == "SUCCESS"){
location.reload();
}else{
alert("Creating User Failed");
}
}
);
在我使用的struts Action类中,
JSONArray jsonArray = (JSONArray) new JSONParser().parse(data);
然后迭代这个数组并得到JOSNObject
来获取所有属性值,即
JOSNObject jsonObject = (JSONObject) jsonArray.get(i);
感谢您的支持。