日期:2014-05-16 浏览次数:20319 次
var userArray=new Array(); for(var i=1;i<=5;i++) { var id=i; var userName="name"+i; userArray.push({id:id, userName:name}); } var users = JSON.stringify(userArray); //记住不是:JSON.tostring(userArray); var url = "testJsonAction"; var params = {"users":users}; $.getJSON(url,params,function(result){ alert(result); });
<action name="testJsonAction" class="TestJsonAction" method="testJson"> <result name="success" type="json"> <param name="root">result</param> </result> </action>
package test; import java.util.HashMap; import java.util.Map; import com.org.json.JSONArray; import com.org.json.JSONException; import com.opensymphony.xwork2.ActionSupport; public class TestJsonAction extends ActionSupport { private String users; private String result; public String testJson() throws JSONException { Map<Long, String> usersMap = new HashMap<Long, String>(); // 将JSON格式的字符串构造成JSON对象 JSONArray jsonArray = new JSONArray(users); for (int i = 0; i < jsonArray.length(); i++) { Long id = jsonArray.getJSONObject(i).getLong("id"); String userName = jsonArray.getJSONObject(i).getString("userName"); usersMap.put(id, userName); } //do your other task; if(条件成立) { result="success"; }else{ result="failure"; } return SUCCESS; } @JSON(serialize=false) public String getUsers() { return users; } public void setUsers(String users) { this.users = users; } @JSON(serialize=false) public String getResult() { return result; } public void setResult(String result) { this.result = result; } }