日期:2014-05-17  浏览次数:20682 次

数据库数据返回json?
怎样将数据库中的数据读取后,以json格式返回?

------解决方案--------------------
后台java实现
------解决方案--------------------
把所读取的数据转为值对象存储,然后借助JSON开源工具将其转化为JSON字符串即可,最后你用Servlet直接通过response.getWriter()回写String即可。


代码啥的可以参考这里:
http://www.blogjava.net/xcp/archive/2008/10/31/json2.html
------解决方案--------------------
类似代码 希望对你有帮助

public String getNoTimeSelect() throws JSONException {
//构建数组
JSONArray jsonArray = new JSONArray();
//构建json串
JSONObject jsonObject;
//转换时间格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//转换时间成年月日
String[] lstGetTime = fileStartTime.split(" ");
fileStartTime = lstGetTime[0];
//查询登录信息
List<TbLogin> loginList = loginService.getTbLoginByTime(fileStartTime,userId);
if(loginList != null && loginList.size() > 0) {
for(TbLogin tbLogin : loginList) {
jsonObject = new JSONObject();
jsonObject.put("id", tbLogin.getUserid());
jsonObject.put("beginTime", sdf.format(tbLogin.getLoginstarttime()));
jsonObject.put("endTime", sdf.format(tbLogin.getLoginendtime()));
jsonArray.put(jsonObject);
}
}
this.renderText(jsonArray.toString());
return null;
}
------解决方案--------------------
Java code

public static JSONObject strToJson() throws SQLException{
        Connection conn=DriverManager.getConnection("数据用户名,密码,驱动字符串");
        PreparedStatement pstmt=conn.prepareStatement("执行的sql语句");
        ResultSet rs=pstmt.executeQuery();
        Map<String,String> map=new HashMap<String,String>();
        //循环取出数据
        if(rs.next()){
            map.put("one",rs.getString(1));
            map.put("two",rs.getString(2));
        }
        JSONObject json=JSONObject.fromObject(map);
        return json;
    }

------解决方案--------------------
一般工程要导入json的jar包,可以参考http://www.json.org/
通常用的是json-lib-2.2.3-jdk15.jar 参考http://json-lib.sourceforge.net/
里面有net.sf.json.JSONObject,net.sf.json.JSONARRAY等类,和相关方法可以使用
------解决方案--------------------
推荐用Gson
------解决方案--------------------
json形式 {"key":"value" ,"date":{["key":"value","key":"value"..],["key":"value",...]}} 可以自己拼。 前台就在回调函数中取就可以 如 function(date) , date.a值就是 aaa , date.date[0].key 就是list的第一个对象的key的value