- 提要
项目中经常使用的json情势数据在前背景完成string与object对象等种种互转相干知识点整顿。 前端:Form Data–>Json Object–>Json String:
jsp片断:
<form action=”” id=”jsonForm”>
cd:<input type="text" id="" name="goodsCd" value="20150904" /><br/> name:<input type="text" id="" name="goodsName" value="che"/>
</form>
js片断:
//具有name、value属性,序列化成一个Object对象
$.fn.serializeObject = function() {var obj = {}; var arr = this.serializeArray(); $.each(arr, function() { if (obj[this.name]) { if (!obj[this.name].push) { obj[this.name] = [ obj[this.name] ]; } obj[this.name].push(this.value || ''); } else { obj[this.name] = this.value || ''; } }); return obj;
};
var jsonForm = $(“#jsonForm”);
// json对象转json字符串
var jsonStr = JSON.stringify(jsonForm.serializeObject());
alert(jsonStr);前端:Json String–>Json Object:
js片断:
jQuery.parseJSON(jsonStr));
前后端:Json Object–>JavaBean:
js片断:
// rb须与背景实体变量称号同名
function getRbJson(){var rbJson = {}; rbJson["rb.goodsType"] = "a"; rbJson["rb.goodsCd"] = "b"; return rbJson;
}
$(function(){$.ajax({ url: "setJsonObject.action", type: 'POST', cache: false, async:false, data: getRbJson(), success: function (text) { }, error: function (jqXHR, textStatus, errorThrown) { alert(jqXHR.responseText); } });
});
java片断:
private RbGoods rb;
public RbGoods getRb() {
return rb;
}
public void setRb(RbGoods rb) {
this.rb = rb;
}
public String setJsonObject() {
System.out.println(rb.getGoodsCd()); return SUCCESS;
}
前后端:Json String–>JavaBean:
js片断:
var rbStr = {};
var rbArray = [];
rbArray.push({goodsCd:’1′,goodsName:’che’});
rbArray.push({goodsCd:’2′,goodsName:’chen’});
rbStr[“jsonArrayStr”] = rbArray;
$.ajax({url: "jsonStrToObject.action", type: 'POST', cache: false, async:false, data: {jsonStr:JSON.stringify(rbArray)}, success: function (text) {}, error: function (jqXHR, textStatus, errorThrown) { alert(jqXHR.responseText); }
});
java片断:
private String jsonStr;
public String getJsonStr() {
return jsonStr;
}
public void setJsonStr(String jsonStr) {
this.jsonStr = jsonStr;
}
public String jsonStrToObject() {
// String转JSON
JSONArray jsonArray = JSONArray.fromObject(jsonStr);
for(int i = 0; i < jsonArray.size(); i++) {
// JSON转object对象
String JOStr = jsonArray.getString(i);
JSONObject JO = JSONObject.fromObject(JOStr);
RbGoods goods =(RbGoods)JSONObject.toBean(JO, RbGoods.class);
System.out.println(goods.getGoodsCd());
}
return SUCCESS;
}
function newchePoint(obj) {
return "<che id=\""+obj.id+
"\" type=\""+obj.type+"\" value=\"\"/>\r\n";
}
- 更新ing…