我正在手动创建JSF中的JSON数据。
以下是我正在做的事情&工作得很好。
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:body>
<ui:composition
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<f:event type="preRenderView" listener="#{MobileLogin.fetNewsData()}" />
</ui:composition>
</h:body>
</html>
public void fetNewsData() {
try {
ConnectToDatabase db = new ConnectToDatabase();
Connection conn = db.makeconnection();
PreparedStatement psmt = conn.prepareStatement("SELECT * FROM news ORDER BY id DESC");
ResultSet rs = psmt.executeQuery();
String json = "[";
int myTotal = 0;
String myDate = "";
while (rs.next()) {
System.out.println("test 002 - " + rs.getString(1));
if (myTotal >= 1) {
json = json + ",";
}
myDate = rs.getString(4);
myDate = myDate.substring(8, 10) + "-" + myDate.substring(5, 7) + "-" + myDate.substring(0, 4);
json = json + "{"
+ "\"id\": \"" + rs.getString(1) + "\","
+ "\"title\": \"" + rs.getString(2) + "\","
+ "\"detailMessage\": \"" + rs.getString(3) + "\","
+ "\"whenAdd\": \"" + myDate + "\""
+ "}";
myTotal++;
}
json = json + "]";
// Show it.
myNewsInJSONFormat = json.toString();
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
externalContext.setResponseContentType("application/json");
externalContext.setResponseCharacterEncoding("UTF-8");
externalContext.getResponseOutputWriter().write(myNewsInJSONFormat);
facesContext.responseComplete();
System.out.println("fina data is " + myNewsInJSONFormat);
if (conn!=null) {
conn.close();
}
} catch (Exception e) {
myNewsInJSONFormat = "";
}
}
一切都运行得很好,但是当我在文本中使用新行和双引号时(特别是在detailMessage中)会出现问题。
新行和双引号的解决方法是什么?
示例JSON数据如下..(带双引号和新行)
[{"id": "6","title": "We can make iPhone app too now...","detailMessage": "Yes!!! You heard it "right"...
We can make iPhone app too with website....","whenAdd": "11-08-2013"}]
答案 0 :(得分:1)
StringEscapeUtils.escapeJavaScript()成功了。
以下是我的代码
+ "\"detailMessage\": \"" + StringEscapeUtils.escapeJavaScript(rs.getString(3)) + "\","
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^