Java 生成Json串

public ActionForward createJson (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		try {
			JSONObject jsonObject = null;
			JSONArray jsonArray = new JSONArray();

			for (int i = 0; i < 10; i++) {
				jsonObject = new JSONObject();
				int x = (int) (Math.random() * 50);
				int y = (int) (Math.random() * 50);

				jsonObject.put("x", new Date().getTime());
				jsonObject.put("y", y);

				jsonArray.add(jsonObject);
			}
			JSONObject json = new JSONObject();
			json.put("total", 10);
			json.put("rows", jsonArray);
			
			System.out.println(json.toString());
			// 返回
			RiaUtils.writeJsonText2Page(json.toString(), response);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

 格式:{"total":10,"rows":[{"x":1435806586289,"y":44},{"x":1435806586601,"y":40},{"x":1435806586601,"y":38},{"x":1435806586601,"y":30},{"x":1435806586601,"y":46},{"x":1435806586601,"y":1},{"x":1435806586601,"y":10},{"x":1435806586601,"y":31},{"x":1435806586601,"y":46},{"x":1435806586601,"y":3}]}

 

猜你喜欢

转载自xinjiatao.iteye.com/blog/2223692