【问题标题】:Error passing JSON object from WebMethod (C#)从 WebMethod (C#) 传递 JSON 对象时出错
【发布时间】:2020-05-01 17:34:53
【问题描述】:

我有一个 C# WebMethod,它从我的 SQL 数据库中获取一些数据,然后将其转换为 JSON 字符串。

这里是 WebMethod

    [WebMethod]
    public object getCustomers() {

        string constr = ConfigurationManager.ConnectionStrings["Indigo2.Properties.Settings.Constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT DISTINCT custid, cust_name FROM [dbo].[customers] WHERE archive = 'No'"))

            {
                cmd.Connection = con;
                List<Customers> customers = new List<Customers>();
                con.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        customers.Add(new Customers
                        {
                            custid = sdr["custid"].ToString(),
                            cust_name = sdr["cust_name"].ToString(),

                    });
                    }
                    con.Close();

                    String result = JsonConvert.SerializeObject(customers);
                    this.Context.Response.ContentType = "application/json; charset=utf-8";
                    this.Context.Response.Write(result);

                    return result;
                }
            }
        } 
    }

我是他们试图在客户端使用 JavaScript 传递这些数据。

这是我的 JS

    function buildSelect(response) {

        alert(JSON.stringify(response));

        var $tulem = $("<select><option value=''>All</option></select>");

        $.each(JSON.parse(response).rows, function (i, item) {
            $("<option></option>", { value: item.custid })
                .text(item.custid)
                .appendTo($tulem);
        });

        return $tulem;
    }

JSON.Parse 失败并出现以下错误

XML 解析错误:语法错误 地点:https://localhost:44338/WebService1.asmx/getCustomers 第 1 行第 1 列:getCustomers:1:1 SyntaxError: JSON.parse: JSON 数据的第 1 行第 722 列的 JSON 数据后出现意外的非空白字符

如果我将我的 JSON 返回到控制台,它看起来像这样。

"[{\"custid\":\"ACC001\",\"cust_name\":\"Accenda Limited\"},{\"custid\":\"ANI001\",\"cust_name\":\"Animal Friends\"},{\"custid\":\"APP001\",\"cust_name\":\"Appello\"},{\"custid\":\"ATL001\",\"cust_name\":\"Atlas Contract Furniture\"},{\"custid\":\"BNS001\",\"cust_name\":\"BNS Ltd\"},{\"custid\":\"HAR001\",\"cust_name\":\"Harrow Health\"},{\"custid\":\"IND001\",\"cust_name\":\"Indigo Integrated Solutions\"},{\"custid\":\"MER001\",\"cust_name\":\"Merton Health Limited\"},{\"custid\":\"POL001\",\"cust_name\":\"Polyhose (UK) Ltd\"},{\"custid\":\"PUR001\",\"cust_name\":\"Purbeck School\"},{\"custid\":\"QUE001\",\"cust_name\":\"Queen Elizabeth's School\"},{\"custid\":\"SER001\",\"cust_name\":\"Serbus Limited\"},{\"custid\":\"STS001\",\"cust_name\":\"STS Defence\"},{\"custid\":\"WIM001\",\"cust_name\":\"Wimborne Academy Trust\"}]<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<anyType xmlns:q1=\"http://www.w3.org/2001/XMLSchema\" d1p1:type=\"q1:string\" xmlns:d1p1=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://tempuri.org/\">[{\"custid\":\"ACC001\",\"cust_name\":\"Accenda Limited\"},{\"custid\":\"ANI001\",\"cust_name\":\"Animal Friends\"},{\"custid\":\"APP001\",\"cust_name\":\"Appello\"},{\"custid\":\"ATL001\",\"cust_name\":\"Atlas Contract Furniture\"},{\"custid\":\"BNS001\",\"cust_name\":\"BNS Ltd\"},{\"custid\":\"HAR001\",\"cust_name\":\"Harrow Health\"},{\"custid\":\"IND001\",\"cust_name\":\"Indigo Integrated Solutions\"},{\"custid\":\"MER001\",\"cust_name\":\"Merton Health Limited\"},{\"custid\":\"POL001\",\"cust_name\":\"Polyhose (UK) Ltd\"},{\"custid\":\"PUR001\",\"cust_name\":\"Purbeck School\"},{\"custid\":\"QUE001\",\"cust_name\":\"Queen Elizabeth's School\"},{\"custid\":\"SER001\",\"cust_name\":\"Serbus Limited\"},{\"custid\":\"STS001\",\"cust_name\":\"STS Defence\"},{\"custid\":\"WIM001\",\"cust_name\":\"Wimborne Academy Trust\"}]</anyType>"

我做错了什么,我该怎么做才能将其更改为标准的干净 JSON 字符串?

更新

这是调用 WebMethod 的地方,它是 dataURL,用于名为 cust_name 的字段,在 JQGRID 的 editoptions 中定义。

        jQuery("#jqquotes").jqGrid({
            url: '../We

bService1.asmx/getDataQuotes',
                datatype: "json",
                mtype: 'POST',
                ajaxGridOptions: { contentType: "application/json" },
                serializeGridData: function (postData) {
                    if (postData.searchField === undefined) postData.searchField = null;
                    if (postData.searchString === undefined) postData.searchString = null;
                    if (postData.searchOper === undefined) postData.searchOper = null;
                    if (postData.filters === undefined) postData.filters = null;
                    return JSON.stringify(postData);
                },
                jsonReader: {
                    root: function (obj) {
                        return typeof obj.d.rows === "string" ? $.parseJSON(obj.d.rows) : obj.d.rows;
                    },
                    page: function (obj) { return obj.d.page; },
                    total: function (obj) { return obj.d.total; },
                    records: function (obj) { return obj.d.records; },
                    repeatitems: false
                },
                loadComplete: function () {
                    $('#jqquoteitems').trigger('reloadGrid');

                },
                loadError: function (jqXHR, textStatus, errorThrown) {
                    alert('HTTP status code: ' + jqXHR.status + '\n' +
                        'textStatus: ' + textStatus + '\n' +
                        'errorThrown: ' + errorThrown);
                    alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
                },
                onSelectRow: function () {
                    showDetailsGrid();
                },
                height: 'auto',
                //autowidth: true,
                rowNum: 5,
                rowList: [5, 10, 15],
                colNames: ['Doc ID', 'Quote #', 'Summary', 'Date', 'Customer', 'Contact', 'custid'],
                colModel: [
                    { name: 'docid', key: true, index: 'docid', width: 55, editable: true },
                    { name: 'quote_number', index: 'quote_number', width: 45, editable: true },
                    { name: 'summary', index: 'summary', width: 160, editable: true, edittype: 'textarea' },
                    {
                        name: 'quote_date', formatter: 'date', datefmt: "d-m-Y", editoptions: { dataInit: initDateEdit },
                        formatoptions: { srcformat: "d/m/Y H:i:s", newformat: "d-m-Y" }, index: 'quote_date', width: 60, editable: true
                    },
                    {
                        name: 'cust_name', index: 'cust_name', width: 140, align: "left", editable: true, edittype: "select",
                        editoptions: {
                            dataUrl: '/WebService1.asmx/getCustomers',
                            buildSelect: buildSelect
                        }
                    },

...

【问题讨论】:

  • 你意识到你在 json 数组后面有 xml 内容吗? \"Wimborne Academy Trust\"}]&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;
  • 如何请求您的 API?你能添加代码吗?
  • 您在客户端 js 上获得的 json 是错误的,因为它同时具有 json 和 xml。能否展示下ajax或api请求从js发送到web方法getCustomers的代码。

标签: javascript c# json


【解决方案1】:

它崩溃了,因为您的 JSON 字符串末尾有 "&lt;anyType&gt;",这对于 JSON 来说是不可解析的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-06
    • 2017-03-02
    • 1970-01-01
    • 2017-08-01
    • 2012-11-07
    • 2014-03-06
    • 1970-01-01
    相关资源
    最近更新 更多