0

我在 JSF 中手动创建 JSON 数据。

以下是我正在做的并且工作正常。

JSF 页面

<?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>

MobileLogin.java

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"}]
4

1 回答 1

1

StringEscapeUtils.escapeJavaScript()成功了。

下面是我的代码

+ "\"detailMessage\": \"" + StringEscapeUtils.escapeJavaScript(rs.getString(3)) + "\","
                            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
于 2013-08-14T09:23:15.367 回答