当需要把一串字符串转成一个json 数组 ,并遍历其中的内容时。
首先要导入 net.sf.json.JSONArray和net.sf.json.JSONObject 两个jar 包
<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'}]" ;
// 一个未转化的字符串
JSONArray json = JSONArray.fromObject(str ); // 首先把字符串转成 JSONArray 对象
if(json.size()>0){
for(int i=0;i<json.size();i++){
JSONObject job = json.getJSONObject(i); // 遍历 jsonarray 数组,把每一个对象转成 json 对象
System.out.println(job.get("name")+"=") ; // 得到 每个对象中的属性值
}
}
前端页面json数组转为字符串
var contracts = [
{id: '1', name: 'yanggb合同1'},
{id: '2', name: 'yanggb合同2'},
{id: '3', name: 'yanggb合同3'},
{id: '4', name: 'yanggb合同4'},
{id: '5', name: 'yanggb合同5'}
];
JSON.stringify()方法将数组转换为JSON数组字符串
JSON.parse()方法把JSON字符串解析为json对象
$.ajax({
type: 'post',
url: 'contract\save',
data: {contracts: JSON.stringify(contracts)},
success: function() {
console.log('保存合同成功!');
}
});
@PostMapping(value = "/contract/save")
@ResponseBody
public void saveContracts(String contracts) {
List<Contract> contractList = JSON.parseArray(contracts, Contract.class);
// 保存操作
}
封装成json数据
function demo(){
var con = {};
con["id"] = 0;
con["name"] = '张三';
con["job"] = '学生';
var json = JSON.stringify(con);
alert("封装成json数据为:"+json);
}
最终结果为:{"id":0,"name":"张三","job":"学生"}
封装成json数组
function arr(){
//定义一个数组
var cons = new Array(3);
for(var i = 0;i<3;i++){
var con = {};
con["id"] = 0;
con["name"] = '张三';
con["job"] = '学生';
cons[i] = con;
}
var json = JSON.stringify(cons);
alert("json数组为:"+json);
}
最终结果为:[{"id":0,"name":"张三","job":"学生"},{"id":0,"name":"张三","job":"学生"},{"id":0,"name":"张三","job":"学生"}]
map转为实体
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.70</version>
</dependency>
Map<String,Object> map=new HashMap<>();
map.put("hotId","dfasfaf454af");
map.put("hotName","小明");
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());