问题描述
- $.getJSON获取一组数据
-
从后台传回的json数据为{"cpu":[100],"mem":[10]}{"cpu":[110],"mem":[11]}{"cpu":[120],"mem":[12]}{"cpu":[130],"mem":[13]}。怎么利用getJSON的方法获得数据,单个{"cpu":[100],"mem":[10]}这样的数据可以获得,但是一组的却不行。我在百度知道上问过,但是没人回答http://zhidao.baidu.com/question/392661669009639965.html。菜鸟哈,劳烦各位看看
解决方案
public static void main(String[] args) {
JSONArray jsret = new JSONArray();
PrintWriter out = response.getWriter();
for (int i = 10; i <= 13; i++) {
JSONArray jsonArray2 = JSONArray.fromObject(i*10);
JSONArray jsonArray3 = JSONArray.fromObject((i));
JSONObject jb = new JSONObject();
jb.put("cpu", jsonArray2);
jb.put("mem", jsonArray3);
jsret.add(jb);
}
out.write(jsret.toString());
out.flush();
}
如果没问题,记得顺手采纳一下
解决方案二:
{"cpu":[100],"mem":[10]}{"cpu":[110],"mem":[11]}{"cpu":[120],"mem":[12]}{"cpu":[130],"mem":[13]}
格式不对,
后台格式变一下
[ {"cpu":[100],"mem":[10]},{"cpu":[110],"mem":[11]},{"cpu":[120],"mem":[12]},{"cpu":[130],"mem":[13]}]
解决方案三:
我的后台代码如下:
for (int i = 10; i <= 13; i++) {
PrintWriter out = response.getWriter();
JSONArray jsonArray2 = JSONArray.fromObject(i*10);
JSONArray jsonArray3 = JSONArray.fromObject((i));
JSONObject jb = new JSONObject();
jb.put("cpu", jsonArray2);
jb.put("mem", jsonArray3);
out.write(jb.toString());
out.flush();
}
请问要怎么在最外框加上方括号呢?
解决方案四:
你可以这么写
for (int i = 10; i <= 13; i++) {
PrintWriter out = response.getWriter();
JSONArray jsonArray2 = JSONArray.fromObject(i*10);
JSONArray jsonArray3 = JSONArray.fromObject((i));
JSONObject jb = new JSONObject();
jb.put("cpu", jsonArray2);
jb.put("mem", jsonArray3);
out.write(jb.toString());
out.flush();PrintWriter out = response.getWriter();
JSONArray jsonArray2 = JSONArray.fromObject(i*10);
JSONArray jsonArray3 = JSONArray.fromObject((i));
JSONObject jb = new JSONObject();
jb.put("cpu", jsonArray2);
jb.put("mem", jsonArray3);
}
out.write(jb.toString());
out.flush();
输出格式为:
{"cpu":[100,110,120,130],"mem":[10,11,12,14]}
时间: 2025-01-30 16:01:50