Js array to json and its implementation in the background

  • 2020-03-29 23:52:51
  • OfStack

Presumably you also encounter similar problems in the development process, if you directly send the array obtained by js to the background, the background is unable to distinguish the array, because js array if it is two-dimensional is like this: 1, zhang SAN,23,2, li si,26

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

Js code is as follows:

    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 = "[" + r.join() + "]";  
    return r;  
    return o.toString();  

Then it is the Java background js string after the json conversion.

com.alibaba.fastjson.JSONArray mainArray=JSON.parseArray(info.getMainparame()); 
     log.debug(" The array size :"+mainArray.size()); 
       for(int i=0;i< mainArray.size();i++){ 
           QybjProduceParam p=new QybjProduceParam(); 
           com.alibaba.fastjson.JSONArray paramObject=(com.alibaba.fastjson.JSONArray)mainArray.get(i); 


As you can see from the Java code, it's two conversions. Each time it's converted to a JSONArray object.

If it's a one-dimensional array you only convert it once.

Related articles: