研究了很多天,终于能够把数据库获取的数据成功转换成jsonObject对象
重要代码:
NoticeDaoImpl.java
try {
conn3 = DBUtil.getConnection();
st3 = conn3.createStatement();
rs3 = st3
.executeQuery("SELECT [noticeID],[range],[expiration],[title],[info]"
+ ",[orgID],[depID],[usersID],[affix],[logDate]"
+ " FROM [WisdomOffice].[dbo].[Notice]");
result3.append("{'noticeList':[");
if (rs3 != null) {
while (rs3.next()) {
int id = rs3.getInt(1);
String range = rs3.getString(2);
String expiration = rs3.getString(3);
String title = rs3.getString(4);
String info = rs3.getString(5);
int orgId = rs3.getInt(6);
int depid = rs3.getInt(7);
int userId = rs3.getInt(8);
String affix = rs3.getString(9);
String logDate = rs3.getString(10);
if (info != null)
info = info.replaceAll("\\s","");
result3.append("{'noticeId':'" + id + "','range':'" + range
+ "','expiration':'" + expiration + "','title':'"
+ title + "','info':'" + info + "','orgID':'"
+ orgId + "','depID':'" + depid + "','usersID':'"
+ userId + "','affix':'" + affix + "','logDate':'"
+ logDate + "'}");
if (!rs3.isLast()) {
result3.append(",");
}
}
}
result3.append("]}");
System.out.println(result3.toString());
} catch (sqlException e) {
// Todo Auto-generated catch block
e.printstacktrace();
result3.append("{'operating':'查询出错了'}]}");
} finally {
DBUtil.freeDB(rs3,st3,conn3);
}
SbgStatisticsHandler.java
/**
* 查询所有
*
* @return
*/
public JSONObject handleIV() {
try {
System.out.println("11Try");
StringBuffer sb = impl.getNoticeAll();
JSONObject object9 = JSONObject.fromObject(sb.toString());
System.out.println(sb.toString());
return object9;
} catch (Exception e) {
System.out.println("erroratch");
e.printstacktrace();
String str = "{errorcode:'0',errormsg:'查询失败'}";
JSONObject object = JSONObject.fromObject(str);
return object;
}
}
TestServlet.java
@Override
protected void service(HttpServletRequest request,
HttpServletResponse response) throws servletexception,IOException {
// Todo Auto-generated method stub
response.setCharacterEncoding("UTF-8");
response.setHeader("content-type","text/html;charset=UTF-8");
PrintWriter writer = response.getWriter();
switch (4) {
case 0:// 查询公司名称
JSONObject jsonObject = handler.handle();
writer.write(jsonObject.toString());
break;
case 1:// 按Id查询
JSONObject object = handler.handleI(11);
writer.write(object.toString());
break;
case 2:// 按Id删除
JSONObject object1 = handler.handleII(188);
writer.write(object1.toString());
break;
case 3:// 按Id和userId更新
// object = handler.handleIII(189);
// writer = response.getWriter();
// writer.write(object.toString());
break;
case 4:// 查询所有
JSONObject object3 = handler.handleIV();
writer.write(object3.toString());
break;
}
}
在研究中遇到了一个问题:json unterminated string at character
最后是因为我的sqlServer数据库中获取的数据里面有换行空格或制表符等特殊符号,我添加了这个判断后,就好了:
if (info != null)
info = info.replaceAll("\\s","");
2014.4.29
Ida
莹和视兴
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。