将String转换成json对象或json数组
这里的SmartProejctEquipmentMap 是我自定的一个实体类,可以自己定义转换。
注意:json字符串中键的名称要和实体类一致。
@Test
public void TestJsonObject() {
String datajson = "" +
"[" +
" {" +
" 'projectId':'00a8de32-422c-4b8d-b945-d9cda7f30a31'," +
" 'projectName':'年产片式元器件7.2亿个、高分子固体电容器3.96亿个等项目(标准厂房、连廊A,甲类仓库,办公楼,宿舍,值班门卫,垃圾房)'," +
" 'iconType':'yc'," +
" 'eqpType':'yc'," +
" 'sn':'SZWJJJ8MQX20200403134027'," +
" 'name':'测试第三方01'," +
" 'wkt':'测试第三方01'," +
" 'sn':'POINT(120.698299 31.272362)'" +
" }," +
" {" +
" 'projectId':'00a8de32-422c-4b8d-b945-d9cda7f30a31'," +
" 'projectName':'测试项目编号名称'," +
" 'iconType':'yc'," +
" 'eqpType':'yc'," +
" 'sn':'FDASDFAFDAFYF89AS6F897DD'," +
" 'name':'扬尘设备001'," +
" 'wkt':'扬尘设备001'," +
" 'sn':'POINT(120.698299 31.272362)'" +
" }" +
"]";
JSONArray jsonArray = JSONArray.parseArray(datajson);
for(int i=0; i<jsonArray.size(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
SmartProejctEquipmentMap myclass = JSONObject.parseObject(object.toJSONString() , SmartProejctEquipmentMap.class);// 将string类型直接封装成对象
System.out.println(myclass.toString());
}
字符串转json数组的解决
前提:当需要把一串字符串转成一个json 数组 ,并遍历其中的内容时。
第一步:
首先导入 net.sf.json.JSONArray和net.sf.json.JSONObject 两个jar 包
Java:
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")+"=") ; // 得到 每个对象中的属性值
}
}
Js:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<SCRIPT LANGUAGE="JavaScript">
var t="{'firstName': 'cyra', 'lastName': 'richardson', 'address': { 'streetAddress': '1 Microsoft way', 'city': 'Redmond', 'state': 'WA', 'postalCode': 98052 },'phoneNumbers': [ '425-777-7777','206-777-7777' ] }";
var jsonobj=eval('('+t+')');
alert(jsonobj.firstName);
alert(jsonobj.lastName);
var t2="[{name:'zhangsan',age:'24'},{name:'lisi',age:'30'},{name:'wangwu',age:'16'},{name:'tianqi',age:'7'}] ";
var myobj=eval(t2);
for(var i=0;i<myobj.length;i++){
alert(myobj[i].name);
alert(myobj[i].age);
}
var t3="[['<a href=# οnclick=openLink(14113295100,社旗县国税局桥头税务所,14113295100,d6d223892dc94f5bb501d4408a68333d,swjg_dm);>14113295100</a>','社旗县国税局桥头税务所','社旗县城郊乡长江路西段']]";
//通过eval() 函数可以将JSON字符串转化为对象
var obj = eval(t3);
for(var i=0;i<obj.length;i++){
for(var j=0;j<obj[i].length;j++){
alert(obj[i][j]);
}
}
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。