java數據轉爲JSONObject,再轉爲JSONArray

今天做到一個接口需求,描述下:

mysql數據庫裏面有6個字段,每個字段有且只有一條記錄,需求是將每個字段+值,作爲一個JSONObject,最後給他返回一個包含6個JSONObject的JSONArray


開始沒有這種想法,只知道javabean+list再轉。所以以此紀念下。。。。

                Connection conn=DBconnection.getConnection();	
		String  sql="select * from explain_";
		ResultSet rs=DBdao.InfoQuery(sql);
		
		JSONObject info1=new JSONObject();
		JSONObject info2=new JSONObject();
		JSONObject info3=new JSONObject();
		JSONObject info4=new JSONObject();
		JSONObject info5=new JSONObject();
		JSONObject info6=new JSONObject();
		if(rs !=null){
			try {
				while(rs.next()){			
				 info1.put("PriceTypeName",rs.getString("CrossRate1"));
				 info1.put("PriceTypeId","CrossRate1");

				 info2.put("PriceTypeName",rs.getString("CrossRate2"));
				 info2.put("PriceTypeId","CrossRate2");

				 info3.put("PriceTypeName",rs.getString("CrossRate3"));
				 info3.put("PriceTypeId","CrossRate3");

				 info4.put("PriceTypeName",rs.getString("CrossRate4"));
				 info4.put("PriceTypeId","CrossRate4");

				 info5.put("PriceTypeName",rs.getString("CrossRate5"));
				 info5.put("PriceTypeId","CrossRate5");

				 info6.put("PriceTypeName",rs.getString("CrossRate6"));
				 info6.put("PriceTypeId","CrossRate6");

			} 
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

		JSONArray ja = new JSONArray(); 
		ja.add(info1);
		ja.add(info2);
		ja.add(info3);
		ja.add(info4);
		ja.add(info5);
		ja.add(info6);		
		out.println(ja);
		out.flush();
		out.close();
		DBconnection.DBclose();
	}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章