Java读取json数组转化成List或Object数组

      在之前的开发中经常遇到将List或Array转换成json传递到web前端,

供前端显示,但是今天我遇到了一个需要将json数组传递到后台,并在后

台转换成list的问题。为此我花费了一段较长的时间,为此我写下这篇博客。

     首先是在前端用js构造json数组,html代码如下:

<TABLE style="width: 900px" id="table">
<pre name="code" class="html">    <tr id="trHtml">
	<td class="tdlabel" nowrap="nowrap"><label><ju:txt value="虚拟账号" />:</label></TD>
	<TD><input type="text" id="payAccNo"  name="payAccNo" vui-name="payAccNo" style="width:100px;" autocomplete="off"/></TD>
	<td class="tdlabel" nowrap="nowrap"><label><ju:txt value="科目号" />:</label></TD>
	<TD>
	<input type="text" id="glCode"  name="glCode" vui-name="glCode" style="width:100px;" autocomplete="off"/>
	</TD>
	<td class="tdlabel" nowrap="nowrap"><label><ju:txt value="货币类型" /><span style="color:red;"> *</span>:</label></TD>
	<TD>
	<select id="ccy" name="ccy" class="ccy" style="width:80px;text-align: center;"  vui-name="ccy"  vui-validate="required:true" > 
	</select>
	<TD/>
	<td class="tdlabel" nowrap="nowrap"><label><ju:txt value="金额" /><span style="color:red;"> *</span>:</label></TD>
	<TD>
	<input type="text" id="amount" name="amount" style="width:80px;"  vui-name="amount"  vui-validate="required:true,type:number" /> 
	<TD/>
	<td class="tdlabel" nowrap="nowrap"><label><ju:txt value="摘要"/><span style="color:red;"> *</span>:</label></TD>
	<TD>
	<textarea id="remark" name="remark" style="width:200px;"  vui-name="remark"  vui-validate="required:true,maxlen:20"> </textarea>
	<TD/>
	<TD style="padding-left:35px;">
	<img id="create" src="img/create.png" style="margin-right:10px"/>
	<TD/>
	<TD style="padding-left:15px;">
	<img id="delete"  src="img/delete.png"/>
	<TD/>
   </tr>				
</TABLE>
 
在需求中需要动态添加和删除tr中的内容以增加一行输入项,为此有如下js代码: 
//绑定添加
			addHTML="<tr>"+$("#trHtml").html()+"</tr>";
			$("#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<String, Object> request = this.getRequestData();
        Map<String, Object> response = this.getResponseData();
        Object handworkAccountList = request.get("handworkAccountList");
        String json = handworkAccountList.toString();
        JSONArray array = JSONArray.fromObject(json);
        List<HandworkAccountDto>  dtoList=new ArrayList<HandworkAccountDto>();
        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<HandworkAccountDto> 也可以是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数组的案例完成。


     



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值