作者:超人 | 来源:互联网 | 2023-09-17 04:08
概要项目中常用的json形式数据在前后台实现string与object对象等各种互转相关知识点整理。前端:FormData–JsonObject–JsonString:jsp片
- 概要
项目中常用的json形式数据在前后台实现string与object对象等各种互转相关知识点整理。 前端:Form Data–>Json Object–>Json String:
jsp片段:
cd:
name:
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 // 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 " "\" type=\""+obj.type+"\" value=\"\"/>\r\n";
}