在之前的开发中经常遇到将List或Array转换成json传递到web前端,
供前端显示,但是今天我遇到了一个需要将json数组传递到后台,并在后
台转换成list的问题。为此我花费了一段较长的时间,为此我写下这篇博客。
首先是在前端用js构造json数组,html代码如下:
:: *: *: *:
在需求中需要动态添加和删除tr中的内容以增加一行输入项,为此有如下js代码:
//绑定添加
addHTML="
"+$("#trHtml").html()+"";$("#handworkAccountForm").find($("#create")).each(function(){
$("#create").die("click");
$("#create").live("click",function(){
$("#table").append(addHTML);
$(".ccy:last").html(modelsHTML);
});
});
//
//绑定删除
$("#handworkAccountForm").find($("#delete")).each(function(){
$("#delete").live("click",function(){
if($("#table tr").length==1){
return
}
$(this).parent().parent().remove();
});
});
其中addHTML是select中的option项,是用ajax从后台load出来的,此处忽略。
其次,需要用js获取个tr项中的输入,构造成json数组,代码如下:
var saveHandworkAccount = function() {
var jsonData={"resourceID":"2020004"};
var handworkAccountList=new Array;
var jsonStr="";
$("#table tr td input,select,textarea").each(function(i){
var name=$(this).attr("name");
var value=$(this).val();
jsonStr=jsonStr+"\""+name+"\":"+"\""+value+"\""+",";
if(i%4==0&i!=0){
jsonStr="{"+jsonStr.substring(0,jsonStr.length-1)+"}";
var a=jQuery.parseJSON(jsonStr);
handworkAccountList.push(a);
jsonStr="";
}
});
jsonData["handworkAccountList"]=JSON.stringify(handworkAccountList);
$.vAjax({
url : "handworkAccountProcess.json",
data : jsonData,
dataType:"json",
success : function(data) {
if(data.errorMsg){
alert(data.errorMsg);
return;
}
if(data.info){
alert(data.info);
location.reload();
}else{
alert("操作失败");
}
},
error : function(jqXhr, textStatus, error) {
alert("加载页面失败!");
}
});
};
构造出来的json格式如下:
{
"handworkAccountList": [
{
"payAccNo": "122",
"glCode": "333",
"ccy": "CNY",
"amount": "44",
"remark": " 5555"
},
{
"payAccNo": "5555",
"glCode": "6666",
"ccy": "CNY",
"amount": "888"
}
],
"resourceID": 2020004
}
最后是后台获取,代码如下:
public void addHandworkAccount(Context context) {
logger.debug("Start addHandworkAccount...");
Map request = this.getRequestData();
Map response = this.getResponseData();
Object handworkAccountList = request.get("handworkAccountList");
String json = handworkAccountList.toString();
JSONArray array = JSONArray.fromObject(json);
List dtoList=new ArrayList();
for (int i = 0; i < array.size(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
dtoList.add((HandworkAccountDto) JSONObject.toBean(jsonObject, HandworkAccountDto.class));
}
logger.debug("addHandworkAccount success...");
}
其中List 也可以是Object数组,HandworkAccountDto
是数据传输对象,用来封装前端传递的参数,代码如下:
public class HandworkAccountDto implements Serializable {
protected String payAccNo;
protected String glCode;
protected String ccy;
protected BigDecimal amount;
protected String remark;
//....省略get,set方法
}
至此,Java读取json数组转化成List或Object数组的案例完成。