有时候需要将从数据库获取的数据封装成json格式,可以使用如下方式拼接
代码
public void getinfo(){
List<Devicealarm> deviceinfo=devicealarmService.findByCondition(condition);
ArrayList list=new ArrayList();
for (Devicealarm obj:deviceinfo){
JSONObject object=new JSONObject();
JSONObject object2=new JSONObject();
JSONArray array=new JSONArray();
object.put("alarmcategory",obj.getAlarmcategory());
object.put("alarmdate",obj.getAlarmdate());
object.put("alarmdesc",obj.getAlarmdesc());
object.put("alarmid",obj.getAlarmid());
object.put("alarmlevel",obj.getAlarmlevel());
object.put("devcategory",obj.getDevcategory());
object.put("devid", obj.getDevid());
object.put("opertype",obj.getOpertype());
object.put("subdevid",obj.getSubdevid());
object2.put("row",object);
object2.put("rowtype","devicealarm");
array.add(object2);
JSONObject Object=new JSONObject();
Object.put("function",1301);
Object.put("type","I");
Object.put("data",array);
list.add(Object);
}
System.out.println(list);
}
拼接的结果示例
[{
"data": [{
"rowtype": "devicealarm",
"row": {
"devid": "test",
"alarmdesc": "IP: test",
"alarmcategory": "test",
"alarmid": "test",
"opertype": "N",
"subdevid": "test",
"devcategory": "test",
"alarmdate": "test",
"alarmlevel": "test"
}
}],
"function": 1001,
"type": "I"
}]