More
More

Json的转换与传递

  • 概要

    项目中常用的json形式数据在前后台实现string与object对象等各种互转相关知识点整理。

  • 前端:Form Data–>Json Object–>Json String:

1
2
3
4
5
☞ 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>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
☞ 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:
1
2
☞ js片段:
jQuery.parseJSON(jsonStr));
  • 前后端:Json Object–>JavaBean:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
☞ 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);
}
});
});
1
2
3
4
5
6
7
8
9
10
11
12
☞ 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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
☞ 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);
}
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
☞ 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…
打赏
手机扫一扫,支持CHE~