Js把Json序列化为Java接受的对象。

时间:2024-10-18 17:36:08

服务器端

Java定义

 data class role(var name: String = "", var remark: String = "")
data class user(var name: String = "", var roles: Array<role> = arrayOf())
data class corp(var name: String = "", var users: Array<user> = arrayOf()); @PostMapping(value = "hi")
fun hiPost(qm: corp, session: HttpSession): String {}

Java接受的格式,Kotlin Test

    @Test
fun testHi() {
var map = JsonMap();
map["name"] = "金维度";
map["users[0].name"] = "张三";
map["users[0].roles[0].name"] = "销售";
map["users[0].roles[0].remark"] = "销售角色";
map["users[0].f"] = "王大,王二"; map["users[1].name"] = "本四";
map["users[1].roles[0].name"] = "开发";
map["users[1].roles[0].remark"] = "开发角色";
map["users[1].roles[1].name"] = "UI";
map["users[1].roles[1].remark"] = "设计师";
// map["createAt"] = 1492762310797; var result = mvc!!.perform(
MockMvcRequestBuilders.post("/hi")
.contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.content(URLEncodedUtils.format(map.ToNameValuePairs(), Charset.defaultCharset()))
)
.andDo(MockMvcResultHandlers.print())
.andReturn(); Assert.assertEquals(result.response.status, 200);
println(result);
}

客户端需要PostBody内容:

 name=%E9%87%91%E7%BB%B4%E5%BA%A6&users%5B0%5D.name=%E5%BC%A0%E4%B8%89&users%5B0%5D.roles%5B0%5D.name=%E9%94%80%E5%94%AE&users%5B0%5D.roles%5B0%5D.remark=%E9%94%80%E5%94%AE%E8%A7%92%E8%89%B2&users%5B1%5D.name=%E6%9C%AC%E5%9B%9B&users%5B1%5D.roles%5B0%5D.name=%E5%BC%80%E5%8F%91&users%5B1%5D.roles%5B0%5D.remark=%E5%BC%80%E5%8F%91%E8%A7%92%E8%89%B2&users%5B1%5D.roles%5B1%5D.name=UI&users%5B1%5D.roles%5B1%5D.remark=%E8%AE%BE%E8%AE%A1%E5%B8%88

客户端

定义:

/**Java方式的序列化。
* @param obj
*/
jv.param_jmap = function (obj) {
var ret = {};
Object.keys(obj).forEach(key => {
var value = obj[key]; if (Array.isArray(value)) {
for (var i in value) {
var m = jv.param_jmap(value[i]);
Object.keys(m).forEach(sk => {
ret[key + "[" + i + "]." + sk] = m[sk];
})
}
}
else if (jv.isPlainObject(value)) {
var m = jv.param_jmap(value);
Object.keys(m).forEach(sk => {
ret[key + "." + sk] = m[sk];
})
}
else {
ret[key] = value;
}
}) return ret;
} jv.param = function (obj) {
var ret = jv.param_jmap(obj);
console.log(ret);
return Object.keys(ret).map(it => {
return encodeURIComponent(it) + "=" + encodeURIComponent(ret[it])
}).join("&");
}

测试:

var data =
{name:"金维度",users:
[
{name:"张三",roles:[{name:"销售",remark:"销售角色"}]},
{name:"本四",roles:[{name:"开发",remark:"开发角色"},{name:"UI",remark:"设计师"}]}
]
} var url = jv.param(data);