简体   繁体   English

如何在Jquery中解析从servlet发送到JSON的arraylist数据

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

I am using servlet to sent data as arraylist to ajax calls.Now on client side i am trying to parse that data into json type but it is giving error as.. 我正在使用servlet将数据作为arraylist发送到ajax调用。现在在客户端我尝试将该数据解析为json类型但是它给出了错误。

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

The values that i am getting ajax success is 我获得ajax成功的价值观是

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

Here is my client side ajax code.. 这是我的客户端ajax代码..

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

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

and here is my servlet code.. 这是我的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();

Please guys help me . 请大家帮帮我 Thanks in advance.. 提前致谢..

You say this is what AJAX returns: 你说这是AJAX返回的:

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

The strings are invalid for JSON; 字符串对JSON无效; it should be: 它应该是:

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

You can use gson and write code like, 您可以使用gson并编写代码,

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

this will allow you to support more complex objects as well. 这将允许您支持更复杂的对象。 Or you can build it yourself as Nikos mentioned. 或者你可以像Nikos提到的那样自己构建它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM