簡體   English   中英

如何在Jquery中解析從servlet發送到JSON的arraylist數據

[英]How to parse arraylist data sent from servlet into JSON in Jquery

我正在使用servlet將數據作為arraylist發送到ajax調用。現在在客戶端我嘗試將該數據解析為json類型但是它給出了錯誤。

SyntaxError:JSON.parse:意外字符var dbdata = JSON.parse(data);

我獲得ajax成功的價值觀是

[INCOMING,0,INETCALL,0,ISD,31.8,LOCAL,197.92,STD,73.2]

這是我的客戶端ajax代碼..

 $(document).ready(function() {
        $.ajax({
            type: 'GET',
            url: 'getdata',
            async:false,
            dataType: "text",
            success: function(data) {

                var dbdata=JSON.parse(data);
                alert(dbdata);
            }
        });
   });

這是我的servlet代碼..

ArrayList callcost = new ArrayList();

    try {
        String strQuery = "";
        ResultSet rs = null;

        Conexion conexiondb = new Conexion();
        conexiondb.Conectar();

        strQuery = "SELECT toc,Sum(callcost) as callcost FROM `asteriskcdrdb`.`processeddata_table` group by toc";

        rs = conexiondb.Consulta(strQuery);

        while (rs.next()) {
            String toc = rs.getString("toc").trim();
            String cost=rs.getString("callcost").trim();
            callcost.add(toc.trim());
            callcost.add(cost.trim());
        }

        out.print(callcost);
        System.out.println(callcost);
        out.close();

請大家幫幫我 提前致謝..

你說這是AJAX返回的:

[INCOMING, 0, INETCALL, 0, ISD, 31.8, LOCAL, 197.92, STD, 73.2]

字符串對JSON無效; 它應該是:

["INCOMING", 0, "INETCALL", 0, "ISD", 31.8, "LOCAL", 197.92, "STD", 73.2]

您可以使用gson並編寫代碼,

Gson gson = new Gson();
String json = gson.toJson(callcost);

這將允許您支持更復雜的對象。 或者你可以像Nikos提到的那樣自己構建它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM