繁体   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