Home > Web Front-end > JS Tutorial > body text

Specific implementation of converting js array to json and parsing it in the background_javascript skills

WBOY
Release: 2016-05-16 17:13:48
Original
1221 people have browsed it

I believe everyone has encountered similar problems during the development process. If the array obtained by js is directly passed to the backend, the backend cannot distinguish the arrays, because if the js array is two-dimensional, it will look like this: 1, Zhang San, 23,2,John Doe,26

So here are the solutions. Hope it can be helpful to everyone

First you need to convert the array into json format in js

js code is as follows:

Copy code The code is as follows:

/**
*js array to json
*
*/
function arrayToJson(o) {
var r = [];
if (typeof o == "string") return "/"" o.replace(/([/'/"//])/g, "//$1").replace(/(/n)/g, "//n").replace(/(/r)/g, "//r").replace(/(/t)/g , "//t") "/"";
if (typeof o == "object") {
if (!o.sort) {
for (var i in o)
r.push(i ":" arrayToJson(o[i]));
if (!!document.all && !/^/n?function/s*toString/(/)/s*/{/n ?/s*/[native code/]/n?/s*/}/n?/s*$/.test(o.toString)) {
r.push("toString:" o.toString. toString());
}
r = "{" r.join() "}";
} else {
for (var i = 0; i < o.length; i ) {
r.push(arrayToJson(o[i]));
}
r = "[" r.join() "]";
}
return r;
}
return o.toString();
}

Then convert the string to json in java background js .

Copy code The code is as follows:

com.alibaba.fastjson.JSONArray mainArray=JSON.parseArray (info.getMainparame());
log.debug("Array size:" mainArray.size());
for(int i=0;i< mainArray.size();i ){
          QybjProduceParam p=new QybjProduceParam();
                                                                                                                                                                 1) .toString());
p.setParamevalue(paramObject.get(2).toString());

params.add(p);
}
info.setParams(params );

It is not difficult to see from the java code that it has been converted twice. Each time it is converted to a JSONArray object.
If it is a one-dimensional array, it will only be converted once.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template