当前位置:   article > 正文

json格式的解析,list如何转换json格式

json格式的解析,list如何转换json格式

list转换成json,然后在js里获取:

        基本格式:

    controller里:         

  JSONObject json = new JSONObject();
json.put("data", weirFlowService.queryWeirFlow(null));
response.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
json.put("status", "1");
json.put("info", "查询成功!");
out.write(json.toString());

js里:

function getflowdata(stcd) {
$.ajax({
url : "getflowdata.do",
type : "post",
data:{stcd:stcd},
dataType : "json",
success : function(result) {

var data = result.data;        或 var allchart = JSON.parse(result).data;


eg1

js:

//渗流量数据
function getflowdata(stcd) {
$.ajax({
url : "getflowdata.do",
type : "post",
data:{stcd:stcd},
dataType : "json",
success : function(result) {

if (result && result.data) {
var html = [];var DELETE;
var data = result.data;

html.push('<table  class="gridcss" id="realFlow" style="width:100%;">');
html.push('<caption>渗流量数据管理</caption>');
html.push('<thead>');
html.push('<tr style="bgcolor:green"><th style="display:none;"><span >ID</span></th><th><span style="font-weight:bold;color:#000000;">所属水库或河流</span></th><th><span style="font-weight:bold;color:#000000;">测站编码</span></th><th><span style="font-weight:bold;color:#000000;">测站名称</span></th><th><span style="font-weight:bold;color:#000000;">监测时间</span></th><th><span style="font-weight:bold;color:#000000;">量水堰水位</span></th><th><span style="font-weight:bold;color:#000000;">水位趋势</span></th><th><span style="font-weight:bold;color:#000000;">监测渗流量(mm)</span></th><th><span style="font-weight:bold;color:#000000;">累计渗流量(mm)</span></th><th><span style="font-weight:bold;color:#000000;">压力光栅波长(mm)</span></th><th><span style="font-weight:bold;color:#000000;">温补光栅波长(mm)</span></th><th><span style="font-weight:bold;color:#000000;">备注</span></th><th><span style="font-weight:bold;color:#000000;">操作</span></th></tr>');
html.push('</thead>');
for (var i = 0; i < data.length; i++) {
year=data[i].tm.year-100;month=data[i].tm.month+1;date=data[i].tm.date;
hours=data[i].tm.hours;minutes=data[i].tm.minutes;second=data[i].tm.seconds;nanos=data[i].tm.nanos;
html.push('<tr>');
html.push('<td style="display:none;">');
html.push(data[i].id);
html.push('</td><td>');
html.push(data[i].rsvrcd);
html.push('</td><td>');
html.push(data[i].stcd);
html.push('</td><td>');
html.push(data[i].stnm);
html.push('</td><td>');
html.push("20"+year+"-"+(month==0?"00":(month<10?"0"+month:month))+"-"+(date==0?"--":(date<10?"0"+date:date))+" "+(hours==0?"00":(hours<10?"0"+hours:hours))+":"+(minutes==0?"00":(minutes<10?"0"+minutes:minutes))+":"+(second==0?"00":(second<10?"0"+second:second)));
//html.push(data[i]['tm'].toString());
html.push('</td><td>');
html.push(data[i].rz);
html.push('</td><td>');
html.push(data[i].direct);
html.push('</td><td>');
html.push(data[i].weir_flow);
html.push('</td><td>');
html.push(data[i].total_flow);
html.push('</td><td >');
html.push(data[i].wavelength1);
html.push('</td><td >');
html.push(data[i].wavelength2);
html.push('</td><td >');
html.push(data[i].remark);
html.push('</td><td align="center">');
html.push('<div style="width: 140px;">');
html.push('<div class="btns edit_btns" style="float: left;" model="edit" title="修改菜单" οnclick="edit_lineflow(this);"></div>');
html.push('<div class="btns del_btns" style="float:right" model="delete" title="删除菜单" οnclick="delete_lineflow(this);"></div>');
html.push('</div>');
html.push('</td>');
html.push('</tr>');
}
html.push('</table>');


$("#mains1").html(html.join(""));
Paging.setTableColor("realFlow");
}
}
});
}

controller:

// 加载渗流量数据管理
@RequestMapping(value = "getflowdata")
public void getflowdata(HttpServletRequest request,
HttpServletResponse response) {
Map<String, Object> queryParams = new HashMap<String, Object>();
String stcd = EncodeFilter.encode(request.getParameter("stcd"));
JSONObject json = new JSONObject();
if (stcd.equals("quanbu")) {


json.put("data", weirFlowService.queryWeirFlow(null));


} else {
queryParams.put("stcd", stcd);
json.put("data", weirFlowService.queryWeirFlow(queryParams));
}
try {
response.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
json.put("status", "1");
json.put("info", "查询成功!");
out.write(json.toString());



} catch (IOException e) {
logger.error(e.getLocalizedMessage());
}
return;        //没有返回值
}


eg2.

/**
 * 加载监测项目
 */
function loadItemInfo() {
$("#stationType").empty();
$.ajax({
url : appPath + "/queryitems.do",

dataType : "json",
success : function(result) {
var data = result.data;
for (var i = 0; i < data.length; i++) {
if (data[i].item_id != "displsmt") {
$("#stationType").append('<option value="'
+ data[i].item_id + '">' + data[i].item_name
+ '</option>');
}
}
var itemId = $("#stationType").val();
loadStationId(itemId);
}
});
}


// 水情统计报表监测项目查询
@RequestMapping(value = "queryitems")
public void queryitems(
HttpServletRequest request, HttpServletResponse response

) {



JSONObject json = new JSONObject();
json.put("data", itemsService.queryItems(null));

try {
response.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
json.put("status", "1");
json.put("info", "查询成功!");
out.write(json.toString());


} catch (IOException e) {
logger.error(e.getLocalizedMessage());
}
return ;


}

eg3.

function getrainchart(btn){//把图形函数放在ajax函数里,使用它的获取值
 var data2=new Array() ;var data3 = new Array();var data1 =new Array() 
 var data11 =[] ;var data22 =new Array() ;//把ajax里定义的变量赋给全局变量(ajax不好写全局变量)
 var data33 = [];var times=new Array();
var  years=new Array();var months=new Array();var dates=new Array();var hours=new Array();var minutes=new Array();var seconds=new Array();var nanos=new Array();
var stcd1=$(btn).parent().parent().children("td").eq(0).find("select").val();
var tmbegin1=$(btn).parent().parent().children("td").eq(1).find("input").val();
var tmend1=$(btn).parent().parent().children("td").eq(2).find("input").val();
// var stcd=$("#stationId").val();
var stcd="";
var tmbegin=$("#tmbegin").val();
var tmend=$("#tmend").val();
var data = {
    stcd:stcd,


};
    var itemId=$("#stationType").val();
var url = "";var name="";var kk="";
if (itemId == "PP") {
url =  "rainsspic.do";
name="降雨实时图(单位:mm)";
kk="实时雨量";
} else if (itemId == "ZZ") {
url =  "watersspic.do";
name="水位实时图(单位:m)";
kk="实时水位";
} else if (itemId == "BB") {
url =  "evapsspic.do";
name="蒸发实时图(单位:mm)";
kk="实时蒸发";
} else if (itemId == "TP") {
url =  "tempsspic.do";
name="气温实时图(单位:℃)";
kk="实时气温";
} else if (itemId == "RZ") {
url =  "levelsspic.do";
name="渗压计水位实时图(单位:m)";
kk="实时渗压计水位";
} else if (itemId == "WF") {
url =  "flowsspic.do";
name="渗流量实时图(单位:m3)";
kk="实时渗流量";
} else {
return;
}
$.ajax({


type : "post",
   data:data,
url : url,
async: false,
success : function(msg) {


var allchart = JSON.parse(msg).data;

for (var i = 0; i < allchart.length; i++) {

if (itemId == "PP") {
years[i] = "2"+allchart[i].tm.year-100; 
 
     months[i] = allchart[i].tm.month + 1 < 10 ? "0" + (allchart[i].tm.month + 1) : allchart[i].tm.month + 1;
    
     dates[i] = allchart[i].tm.date  < 10 ? "0" + (allchart[i].tm.date) : allchart[i].tm.date;
    
     hours[i] = allchart[i].tm.hours  < 10 ? "0" + (allchart[i].tm.hours) : allchart[i].tm.hours;
    
     minutes[i] = allchart[i].tm.minutes  < 10 ? "0" + (allchart[i].tm.minutes) : allchart[i].tm.minutes;
   
    seconds[i] = allchart[i].tm.seconds < 10 ? "0" + (allchart[i].tm.seconds) : allchart[i].tm.seconds;
   
    times[i]=years[i]+"-"+months[i]+"-"+dates[i]+" "+hours[i]+":"+minutes[i]+":"+seconds[i];
data1.push(allchart[i].stcd);
        data22[i]=(allchart[i].rain);
        data33.push(allchart[i].tm);
       
               data2[i]=data22[i] ;
                data3[i]=data33[i]
} else if (itemId == "ZZ") {




// 加载渗流量数据管理图表
@RequestMapping(value = "weirflowmnpic")
public void weirflowmnpic(HttpServletRequest request,
HttpServletResponse response) {
Map<String, Object> queryParams = new HashMap<String, Object>();
Map<String, Object> queryParams1 = new HashMap<String, Object>();


String stcd = EncodeFilter.encode(request.getParameter("stcd"));
String tmend1 = EncodeFilter.encode(request.getParameter("tmend"));


String tmbegin1 = EncodeFilter.encode(request.getParameter("tmbegin"));
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


// 默认取最近四周的时间
Calendar cal = Calendar.getInstance();
java.util.Date tmbegin2 = cal.getTime();
java.sql.Timestamp tmbegin = null;
if (!isNull(tmbegin1)) {
try {
tmbegin2 = (java.util.Date) sdf.parse(tmbegin1);
tmbegin = new java.sql.Timestamp(tmbegin2.getTime());


} catch (ParseException e) {


e.printStackTrace();
}


}


java.util.Date tmend2 = cal.getTime();
java.sql.Timestamp tmend = null;
if (!isNull(tmend1)) {
try {
tmend2 = (java.util.Date) sdf.parse(tmend1);


tmend = new java.sql.Timestamp(tmend2.getTime());


} catch (ParseException e) {


e.printStackTrace();
}


}
String nowtime2 = sdf.format(cal.getTime());
cal.add(Calendar.WEEK_OF_YEAR, -4);
String nowtime1 = sdf.format(cal.getTime());


if (!isNull(tmbegin1)) {
queryParams.put("tmbegin", tmbegin1);
} else {
queryParams.put("tmbegin", nowtime1);


}
if (!isNull(tmend1)) {
queryParams.put("tmend", tmend1);
} else {
queryParams.put("tmend", nowtime2);


}
JSONObject json = new JSONObject();
List<Stations> listrainstcd = weirFlowService
.queryStationsweirflow(null);


json.put("legend", weirFlowService.queryStationsweirflow(null));


if (stcd.equals("quanbu")) {
stcd = "";
}
List<Map<String, Object>> list = weirFlowService.weirflowmnpic(stcd,
(String) queryParams.get("tmbegin"),
(String) queryParams.get("tmend"));


JSONArray jsonArr = new JSONArray();
Map<String, EcharsData> jsonMap = new HashMap<String, EcharsData>();
for (Map<String, Object> map : list) {
String jstcd = (String) map.get("stcd");
String jtm = (String) map.get("tm");
Double weirflow = (Double) map.get("weir_flow");
BigDecimal jweirflow = new BigDecimal(weirflow);
if (jsonMap.containsKey(jstcd)) {
EcharsData edata = jsonMap.get(jstcd);
edata.getTmlist().add(jtm);
edata.getRainlist().add(jweirflow);
} else {
EcharsData edata = new EcharsData();


edata.setStcd(jstcd);
edata.getTmlist().add(jtm);
edata.getRainlist().add(jweirflow);
jsonMap.put(jstcd, edata);
}
}


Iterator it = jsonMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String jstcd = (String) entry.getKey();
EcharsData edata = (EcharsData) entry.getValue();
JSONObject jsonObj = new JSONObject();
jsonObj.put("name", jstcd);
jsonObj.put("type", "bar");
jsonObj.put("barMinHeight", 10);
jsonObj.put("tm", edata.getTmlist().toArray());
jsonObj.put("barMaxWidth", 40);
jsonObj.put("data", edata.getRainlist().toArray());


if (json.get("tmdata") == null) {
json.put("tmdata", edata.getTmlist().toArray());
}
jsonArr.add(jsonObj);
}


json.put("data", jsonArr);
try {
response.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
json.put("status", "1");
json.put("info", "查询成功!");
out.write(json.toString());



} catch (IOException e) {
logger.error(e.getLocalizedMessage());
}
SimpleDateFormat sdfg = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


return;
}


从接口里获取数据:


String urlneilao="http://192.168.1.15:8080/pingshan-service/data/Query1?sttp=NL";
String dataneilao=result(urlneilao);//这个接口的方法是返回string类型的数据
int indexdaoneilao=dataneilao.indexOf("{");
String resultdaoneilao=dataneilao.substring(indexdaoneilao);
String resultdaoneilao2=resultdaoneilao.replace(")","");
// 得到一个json对象
JSONObject jsObjneilao = JSONObject.fromObject(resultdaoneilao2);
JSONArray jsonArrayneilao = jsObjneilao.getJSONArray("data");

                                          HashMap queryParams = new HashMap();
                        queryParams.put("neilao", jsonArrayneilao);

根据接口地址获取数据通用方法:

public String result(String urls) {
String url = urls;
// 地址对象
URL webUrl = null;
try {
webUrl = new URL(url);
} catch (MalformedURLException e) {

e.printStackTrace();
}
// 建立远程连接
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) webUrl.openConnection();
} catch (IOException e) {

e.printStackTrace();
}
// 得到输入流
InputStream ins = null;
try {
ins = conn.getInputStream();
} catch (IOException e) {

e.printStackTrace();
}


// 字符读取流
BufferedReader bfr = null;
try {
bfr = new BufferedReader(new InputStreamReader(ins,
"UTF-8"));
} catch (UnsupportedEncodingException e) {

e.printStackTrace();
}
// 使用字符串构造器,将读取的每一行数据拼接起来
StringBuffer sb = new StringBuffer();


String content = null;
try {
while ((content = bfr.readLine()) != null) {
sb.append(content);
}
} catch (IOException e) {

e.printStackTrace();
}
// 关闭字符流
try {
bfr.close();
} catch (IOException e) {

e.printStackTrace();
}
// 释放连接
conn.disconnect();
// 得到返回的字符串
String data = sb.toString();
return data;
}

下面是一些接口:

/**
* 查询测站点的实时数据

* @param sttp
* @param stcd
* @param request
* @param response
* @return
*/
@RequestMapping("/data/Query")
@ResponseBody
public String queryData(@RequestParam(value = "sttp") String sttp,
@RequestParam(value = "stcd", required = false) String stcd,
HttpServletRequest request, HttpServletResponse response) {

log.info("query data, receive http request from " + request.getRemoteAddr());

if (dataQueryJDBCTemplate == null) {
dataQueryJDBCTemplate = (DataQueryJDBCTemplate) PingshanApp.context.getBean("dataQueryJDBCTemplate");
}

//Map json = new HashMap();
JSONObject json = new JSONObject();
try {
/*DataQueryJDBCTemplate dataQueryJDBCTemplate = (DataQueryJDBCTemplate) PingshanApp.context
.getBean("dataQueryJDBCTemplate");*/
List<Map<String, Object>> list = null;
switch (sttp) {
case "ZZ":
list = new ArrayList<Map<String, Object>>();
Set<String> stnmSet = new HashSet<String>();
// 如果坪山新区和市水务局都有监测的站点,以坪山新区的数据为准
for (Map<String, Object> map : dataQueryJDBCTemplate.queryWaterLevel(stcd)) {
String stnm = map.get("stnm").toString();
if (!stnmSet.contains(stnm)) {
list.add(map);
stnmSet.add(stnm);
}
}
break;
case "NL":
list = dataQueryJDBCTemplate.queryNeilaodian(stcd);
break;
case "PP":
list = dataQueryJDBCTemplate.queryRain(stcd);
break;
case "BB":
list = dataQueryJDBCTemplate.queryEvap(stcd);
break;
case "TP":
list = dataQueryJDBCTemplate.queryTemper(stcd);
break;
case "RZ":
list = dataQueryJDBCTemplate.queryOsmodata(stcd);
break;
case "WF":
list = dataQueryJDBCTemplate.queryWeirflow(stcd);
break;
case "ALL":
list = dataQueryJDBCTemplate.queryAllStation(stcd);
break;
}


json.put("data", list);
json.put("status", "1");
json.put("info", "查询成功!");
} catch (Exception e) {
e.printStackTrace();
json.put("status", "0");
json.put("info", "查询失败!");
}
log.info("end query data.");
/*try {
response.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
out.write("\""+json.toString()+"\"");
} catch (IOException e) {
log.error(e.getLocalizedMessage());
}*/
return json.toString();          //返回string 类型的的数据
//return "{\"data\":[{\"stcd\":\"P1002\",\"tm\":\"2015-12-14 10:20:00\",\"z\":23.000},{\"stcd\":\"RR011\",\"tm\":\"2015-11-14 00:12:12\",\"z\":15.000}],\"status\":\"1\",\"info\":\"查询成功!\"}";
}

/**
* 查询河道信息
* @param stcd
* @param request
* @param response
* @return
*/
@RequestMapping("/data/queryReservoir")
@ResponseBody
public Object queryReservoir(@RequestParam(value = "stcd", required = false) String stcd) {
JSONObject json = new JSONObject();
try {
List<Map<String, Object>> list = dataQueryJDBCTemplate.queryReservoir(stcd);
json.put("data", list);
json.put("status", "1");
json.put("info", "查询成功!");
} catch (Exception e) {
e.printStackTrace();
json.put("status", "0");
json.put("info", "查询失败!");
}
log.info("end query data.");
return json;
}

/**
* 查询河道信息
* @param stcd
* @param request
* @param response
* @return
*/
@RequestMapping("/data/queryRiver")
@ResponseBody
public Object queryRiver(@RequestParam(value = "stcd", required = false) String stcd) {
JSONObject json = new JSONObject();
try {
List<Map<String, Object>> list = dataQueryJDBCTemplate.queryRiver(stcd);
json.put("data", list);
json.put("status", "1");
json.put("info", "查询成功!");
} catch (Exception e) {
e.printStackTrace();
json.put("status", "0");
json.put("info", "查询失败!");
}
log.info("end query data.");
return json;
}

/**
* 查询河道信息
* @param stcd
* @param request
* @param response
* @return
*/
@RequestMapping("/data/queryStation")
@ResponseBody
public Object queryStation(@RequestParam(value = "stcd", required = false) String stcd) {
JSONObject json = new JSONObject();
try {
List<Map<String, Object>> list = dataQueryJDBCTemplate.queryStation(stcd);
json.put("data", list);
json.put("status", "1");
json.put("info", "查询成功!");
} catch (Exception e) {
e.printStackTrace();
json.put("status", "0");
json.put("info", "查询失败!");
}
log.info("end query data.");
return json;    //返回json 类型的的数据
}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/366860
推荐阅读
相关标签
  

闽ICP备14008679号