无法解析来自服务器的 JSON 数据

Posted

技术标签:

【中文标题】无法解析来自服务器的 JSON 数据【英文标题】:JSON data from server could not be parsed 【发布时间】:2012-03-18 15:29:58 【问题描述】:

我收到“DataTables 警告:。这是由 JSON 格式错误引起的” 我知道这可能是其他线程的副本,我在代码中使用了 java 和 dataTables。我得到的是 JSON 格式的输出,但在打印时客户端无法识别它。

当我验证 http://jsonlint.com/ 中的 JSON 对象时,它的格式正确。我不确定是什么导致了这个错误。

"iTotalRecords":5,"sEcho":"1","aaData":[["V2993ASFKH230943","本田","雅阁"],["V2993A39SNF30943","本田","CRV"] ,["V4833A39SNF30943","讴歌","TSX"],["V4833RE9SNF30943","讴歌","TL"],["V9383RE9SNF30943","讴歌","MDX"]],"iTotalDisplayRecords":5

任何帮助将不胜感激。

谢谢

编辑

try 
            JSONObject jsonResponse = new JSONObject();

            jsonResponse.put("sEcho", sEcho);
            jsonResponse.put("iTotalRecords", iTotalRecords);
            jsonResponse.put("iTotalDisplayRecords", iTotalDisplayRecords);

            while (itr.hasNext()) 
                Map rs = (Map) itr.next();
                FleetEquipment eqpmt = new FleetEquipment();
                eqpmt.setVinNumber((String) rs.get("VIN_ID"));
                eqpmt.setMake((String) rs.get("MAKE"));
                eqpmt.setModel((String) rs.get("MODEL"));
                JSONArray row = new JSONArray();
                row.put(eqpmt.getVinNumber()).put(eqpmt.getMake())
                        .put(eqpmt.getModel());
                data.put(row);

            

            jsonResponse.put("aaData", data);

            response.setContentType("application/json");
            response.getWriter().print(jsonResponse.toString());
         catch (JSONException e) 
            // TODO Auto-generated catch block
            e.printStackTrace();
            response.setContentType("text/html");
            response.getWriter().print(e.getMessage());
        

编辑 1

<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>

<portlet:defineObjects/>

<portlet:resourceURL var="listURL" id="list" escapeXml="false"/>
<script type="text/javascript">
$(document).ready(function () 
            $('#listTable').dataTable(
                "bServerSide": true,
                "sAjaxSource": "<%=listURL.toString()%>",
                "bProcessing": true,
                "sPaginationType": "full_numbers",
                "bJQueryUI": true
            );
        );

</script></head>
<body>

<table id="listTable">
    <thead>
        <tr>
            <th>VIN ID</th>
            <th>MAKE</th>
            <th>MODEL</th>
            <th>MODEL1</th>
            <th>Model2</th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

【问题讨论】:

你确定,上面提到的 JSON 中没有任何额外的词吗?我的意思是任何错误? 是的..我已经在上面提到的链接中验证了。 我知道你已经验证过了,但是你在萤火虫中检查过,至于最终的结果是什么。那是服务器的萤火虫输出吗?可能是您正在验证正确的 json,但它不是从最终输出中获取的。那么你有没有从最终输出中取出它,比如 firefug? 您能否发布尝试在服务器端解析 JSON 的代码? 是的,这就是我在萤火虫中得到的响应。 【参考方案1】:

[不是问题的答案,而是工具输入]

http://jsonviewer.stack.hu/

这个工具确实有助于理解外部 JSON 对象的结构。这可能不是您问题的答案,但是,这有助于我用 python 代码很好地理解和解析它,它也是一个 JSON 验证器。

【讨论】:

【参考方案2】:
\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\r\n VIN ID MAKE MODEL ","
status ":200,"
statusText ":"
OK ","
fnServerData ":"
function (e, j, l, k) \n k.jqXHR = i.ajax(
        url: e,
        data: j,
        success: function (e) 
            i(k.oInstance).trigger(\"xhr\", k);l(e);, dataType: \"json\", cache: !1, type: k.sServerMethod, error: function (e, i) \"parsererror\" == i && alert(\"DataTables warning: JSON data from server could not be parsed. This is caused by a JSON formatting error.\"););\n", "aoServerParams": [],
            "sServerMethod": "GET",
            "fnFormatNumber": "function (e) \n if (1000 > e) \n return e;\n \n for (var i = e + \"\", e = i.split(\"\"), j = \"\", i = i.length, l = 0; l < i; l++) \n 0 === l % 3 &&\n 0 !== l && (j = this.oLanguage.sInfoThousands + j), j = e[i - l - 1] + j;\n \n return j;\n",
            "aLengthMenu": [10, 25, 50, 100],
            "iDraw": 1,
            "bDrawing": true,
            "iDrawError": -1,
            "_iDisplayLength": 10,
            "_iDisplayStart": 0,
            "_iDisplayEnd": 0,
            "_iRecordsTotal": 0,
            "_iRecordsDisplay": 0,
            "bJUI": true,
            "oClasses": 
                "sTable": "dataTable",
                "sPagePrevEnabled": "fg-button ui-button ui-state-default ui-corner-left",
                "sPagePrevDisabled": "fg-button ui-button ui-state-default ui-corner-left ui-state-disabled",
                "sPageNextEnabled": "fg-button ui-button ui-state-default ui-corner-right",
                "sPageNextDisabled": "fg-button ui-button ui-state-default ui-corner-right ui-state-disabled",
                "sPageJUINext": "ui-icon ui-icon-circle-arrow-e",
                "sPageJUIPrev": "ui-icon ui-icon-circle-arrow-w",
                "sPageButton": "fg-button ui-button ui-state-default",
                "sPageButtonActive": "fg-button ui-button ui-state-default ui-state-disabled",
                "sPageButtonStaticDisabled": "fg-button ui-button ui-state-default ui-state-disabled",
                "sPageFirst": "first ui-corner-tl ui-corner-bl",
                "sPagePrevious": "previous",
                "sPageNext": "next",
                "sPageLast": "last ui-corner-tr ui-corner-br",
                "sStripeOdd": "odd",
                "sStripeEven": "even",
                "sRowEmpty": "dataTables_empty",
                "sWrapper": "dataTables_wrapper",
                "sFilter": "dataTables_filter",
                "sInfo": "dataTables_info",
                "sPaging": "dataTables_paginate fg-buttonset ui-buttonset fg-buttonset-multi ui-buttonset-multi paging_",
                "sLength": "dataTables_length",
                "sProcessing": "dataTables_processing",
                "sSortAsc": "ui-state-default",
                "sSortDesc": "ui-state-default",
                "sSortable": "ui-state-default",
                "sSortableAsc": "ui-state-default",
                "sSortableDesc": "ui-state-default",
                "sSortableNone": "ui-state-default",
                "sSortColumn": "sorting_",
                "sSortJUIAsc": "css_right ui-icon ui-icon-triangle-1-n",
                "sSortJUIDesc": "css_right ui-icon ui-icon-triangle-1-s",
                "sSortJUI": "css_right ui-icon ui-icon-carat-2-n-s",
                "sSortJUIAscAllowed": "css_right ui-icon ui-icon-carat-1-n",
                "sSortJUIDescAllowed": "css_right ui-icon ui-icon-carat-1-s",
                "sSortJUIWrapper": "DataTables_sort_wrapper",
                "sSortIcon": "DataTables_sort_icon",
                "sScrollWrapper": "dataTables_scroll",
                "sScrollHead": "dataTables_scrollHead ui-state-default",
                "sScrollHeadInner": "dataTables_scrollHeadInner",
                "sScrollBody": "dataTables_scrollBody",
                "sScrollFoot": "dataTables_scrollFoot ui-state-default",
                "sScrollFootInner": "dataTables_scrollFootInner",
                "sFooterTH": "ui-state-default"
            ,
            "bFiltered": true,
            "bSorted": true,
            "bSortCellsTop": false,
            "oInit": 
                "bServerSide": true,
                "sAjaxSource": "/wps/myportal/!ut/p/b1/hc09DoJAEIbhs3CCGX5kl3IRdVGiolFkG7Mho2IQEkAKTy8aGwt0ukmeLy8oSE3PctAeWY4LB1Cl7vKzbvOq1MXrV-6RBz73fVMg9-QUw0j6bCLmiGj2IO3BeCakwyJEPuImhkLumLsNLBT2v30C6psgrlhP7Jlki72Fof0BvxJvgAMnEJayulGfShUbDMUISU1Nda8zgs2pIGqjvGkhznR2oYg6Ktb6THBThRde2UMIw3gC131G1Q!!/",
                "bProcessing": true,
                "sPaginationType": "full_numbers",
                "bJQueryUI": true
            ,
            "aoDestroyCallback": [],
            "fnRecordsTotal": "function () \n return this.oFeatures.bServerSide ? parseInt(this._iRecordsTotal, 10) : this.aiDisplayMaster.length;\n",
            "fnRecordsDisplay": "function () \n return this.oFeatures.bServerSide ? parseInt(this._iRecordsDisplay, 10) : this.aiDisplay.length;\n",
            "fnDisplayEnd": "function () \n return this.oFeatures.bServerSide ? !1 === this.oFeatures.bPaginate || - 1 == this._iDisplayLength ? this._iDisplayStart + this.aiDisplay.length : Math.min(this._iDisplayStart + this._iDisplayLength, this._iRecordsDisplay) : this._iDisplayEnd;\n",
            "sInstance": "fleetList",
            "iTabIndex": 0,
            "fnStateLoad": "function (e) \n var e = this.oApi._fnReadCookie(e.sCookiePrefix + e.sInstance), j;\n try \n j = \"function\" === typeof i.parseJSON ? i.parseJSON(e) : eval(\"(\" + e + \")\");\n  catch (l) \n j = null;\n \n return j;\n",
            "fnStateSave": "function (e, i) \n this.oApi._fnCreateCookie(e.sCookiePrefix + e.sInstance, this.oApi._fnJsonString(i), e.iCookieDuration, e.sCookiePrefix, e.fnCookieCallback);\n",
            "iInitDisplayStart": -1,
            "nTableReinsertBefore": null
            ],
        "tablesDisplayData": [
            []
        ],
        "tablesDisplayExtra": [
            []
        ]
    
    ;

【讨论】:

哈——它破坏了 DataTables 调试器!多哈。无论如何 - 在我看来,您的 JSON 响应包含诸如 "script src=\"C:\\workspaces\\WP1\\SpringPortlet\\WebContent\\jquery.dataTables.js\" 之类的东西,这是无效的 json。采取看看 Firebug 中的响应 - 它的内容不是 JSON(有一些 JSON,但也有其他内容)。 我已经从 jsp 页面中删除了该脚本 src,除了那个 JSON 响应之外,我确实有 dataTables 函数以及响应中的表。 查看此示例以查看预期的响应:datatables.net/release-datatables/examples/data_sources/… - DataTables 函数和响应中的表不是预期的 - 只是表的数据。 我在上面的问题中添加了我的 JSP 页面。关于为什么响应显示表格和javascript的任何线索或想法?自从过去 8 小时以来,我一直在努力解决这个问题..

以上是关于无法解析来自服务器的 JSON 数据的主要内容,如果未能解决你的问题,请参考以下文章

使用 Python/Pandas 库无法解析来自 JSON 响应的数据

无法在swift 3中解析Json?

无法将 JSON 数据解析为 Swift

无法解析来自 jQuery Ajax POST 的 Json 结果

无法解析来自谷歌的 json 响应

Gson 无法解析 Kotlin 中的字符串 json 格式数据