gogoWebsite

JSON string array to json array

Updated to 18 days ago

When it is necessary to convert a string into a json array and iterate through the contents in it.
First, import and two jar packages

<dependency>
   <groupId>net.sf.json-lib</groupId>
   <artifactId>json-lib</artifactId>
   <version>2.4</version>
   <classifier>jdk15</classifier>
</dependency>

String str = "[{name:'a',value:'aa'},{name:'b',value:'bb'},{name:'c',value:'cc'},{name:'d',value:'dd'}]" ;// An unconverted string

JSONArray json = JSONArray.fromObject(str ); // First convert the string into a JSONArray object
if(json.size()>0){
  for(int i=0;i<json.size();i++){
    JSONObject job = json.getJSONObject(i);  // traverse the jsonarray array and convert each object into a json object
    System.out.println(job.get("name")+"=") ;  // Get the attribute value in each object
  }
}

Convert json array to string on the front-end page

var contracts = [
   {id: '1', name: 'yanggb contract 1'},
   {id: '2', name: 'yanggb contract 2'},
   {id: '3', name: 'yanggb contract 3'},
   {id: '4', name: 'yanggb contract 4'},
   {id: '5', name: 'yanggb contract 5'}
];

() method converts array to JSON array string
() method parses JSON string into json object

$.ajax({
    type: 'post',
    url: 'contract\save',
    data: {contracts: JSON.stringify(contracts)},
    success: function() {
        console.log('Save the contract successfully!  ');
    }
});
@PostMapping(value = "/contract/save")
@ResponseBody
public void saveContracts(String contracts) {
    List<Contract> contractList = JSON.parseArray(contracts, Contract.class);
    // Save operation
}

Encapsulated into json data

function demo(){
  var con = {};
  con["id"] = 0;
  con["name"] = 'Zhang San';
  con["job"] = 'student';
  var json = JSON.stringify(con);          
  alert("Embroidered into json data as:"+json);  
}The final result is:{"id":0,"name":"Zhang San","job":"student"}

Encapsulated into json array

function arr(){
  //Define an array
  var cons = new Array(3); 
  for(var i = 0;i<3;i++){
    var con = {};
    con["id"] = 0;
    con["name"] = 'Zhang San';
    con["job"] = 'student';
    cons[i] = con;
  }
  var json = JSON.stringify(cons);
  alert("json array is:"+json); 
}The final result is:[{"id":0,"name":"Zhang San","job":"student"},{"id":0,"name":"Zhang San","job":"student"},{"id":0,"name":"Zhang San","job":"student"}]

Convert map to entity

  <!-- /artifact//fastjson -->
        <dependency>
            <groupId></groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.70</version>
        </dependency>
 Map<String,Object> map=new HashMap<>();
 map.put("hotId","dfasfaf454af");
 map.put("hotName","Xiao Ming");
 map.put("hotKey","5464132645");
 map.put("isDelete","1");
 map.put("hotStatus","0");
 String mapString = JSONObject.toJSONString(map);
 Hop hop = JSONObject.parseObject(mapString, Hop.class);
 System.out.println(hop.toString());