StringEscapeUtils.escapeJavaScript() did the trick.
Below is the code I have
+ "\"detailMessage\": \"" + StringEscapeUtils.escapeJavaScript(rs.getString(3)) + "\","
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Question
I am creating JSON data in JSF Manually.
Below is what I am doing & is working perfectly.
<?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 = "";
}
}
All was working perfectly, but the problem occurs WHEN I have new line and double quotes in text (especially at detailMessage).
Any workaround for new line and double quotes?
Sample JSON data is as below.. (with double quotes and new line)
[{"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"}]
Solution
StringEscapeUtils.escapeJavaScript() did the trick.
Below is the code I have
+ "\"detailMessage\": \"" + StringEscapeUtils.escapeJavaScript(rs.getString(3)) + "\","
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^