list转json数组
lights为arraylist
java后台代码:
try {
org.tempuri.TLight[] lights = phlightSoapProxy.getLights();
String jsonStr = null;
JSONArray array = new JSONArray();
/* Json格式的数组形式 */
JSONObject obj;
/* json格式的单个对象形式 */
for ( int i = 0; i < lights.length; i++ )
{
obj = new JSONObject();
/* 依次填充每一个Java实体对象 */
try {
obj.put( "isOpen", 0 );
obj.put( "title", lights[i].getLightName() );
/* json通过put方式以key-value形式填充 */
obj.put( "point", lights[i].getLng() + "|" + lights[i].getLat() );
obj.put( "icon", lights[i].getYxValue() == 0 ? 0 : 1 );
String state = lights[i].getYxValue() == 0 ? "已关闭" : "已开启";
obj.put( "content", "状态:" + state + "<br/>电压:" + lights[i].getVoltage() + "(v)<br/>电流:" + lights[i].getCurrent() + "(A)" );
array.put( obj );
/* 将JSONObject添加入JSONArray */
}
catch ( JSONException e ) {
e.printStackTrace();
}
}
model.addAttribute( "lights", lights );
model.addAttribute( "lightsJSON", array );
}
catch ( RemoteException e ) {
/* TODO Auto-generated catch block */
e.printStackTrace();
}
h ( JSONException e ) {
e.printStackTrace();
}
}
model.addAttribute( "lights", lights );
model.addAttribute( "lightsJSON", array );
}
catch ( RemoteException e ) {
/* TODO Auto-generated catch block */
e.printStackTrace();
}
array 就是最终的json数组
前台html中js 解析:
//标注点数组
var markerArr = '${lightsJSON}';
/* console.log(markerArr); */
markerArr=eval("("+markerArr+")");;
console.log(markerArr);
markerArr 为得到的json数组,js循环数据可以下面操作:
for(var i=0;i<markerArr.length;i++){
var jsonfd = markerArr[i];
var p0 = jsonfd.point.split("|")[0];
var p1 = jsonfd.point.split("|")[1];
var point = new BMap.Point(p0,p1);
if(jsonfd.icon == 0){
var iconImg = createOffIcon();
}else{
var iconImg = createOnIcon();
}
var marker = new BMap.Marker(point,{icon:iconImg});
var iw = createInfoWindow(i);
var label = new BMap.Label(jsonfd.title,{"offset":new BMap.Size(jsonfd.icon.lb-jsonfd.icon.x+0,-20)});
marker.setLabel(label);
map.addOverlay(marker);
label.setStyle({
borderColor:"#808080",
color:"#333",
cursor:"pointer"
});
浏览器中得到结果: