簡體   English   中英

返回帶有引號的JsonResult

[英]Return JsonResult with apostrophes

據我所知,我收到解析器錯誤,因為我返回的某些數據包含撇號。

我得到的錯誤:

SyntaxError:jQuery.parseJSON的Object.parse(本機)輸入意外結束...

我的JavaScript:

var viewModel = kendo.observable({
    hospitalDataSource: new kendo.data.DataSource({
        transport: {
            read: {
                url: "/Hospital/GetHospitals",
                dataType: "json",
                type: "GET"
            },
            schema: {
                model: {
                    id: "Id",
                    fields: {
                        ProviderId: { type: "number" },
                        Name: { type: "string" },
                        Active: { type: "string" }
                    }
                }
            },
            errors: "errorMsg"
        },
        pageSize: 10,
        error: function (e) {
            toastr.options = {
                "positionClass": "toast-bottom-full-width"
            };
            toastr.error('There was an error:' + e.errors, 'Uh Oh!');
            this.cancelChanges();
        },
        serverPaging: false,
        serverFiltering: false,
        serverSorting: false
    }),
})

控制器JsonResult:

[HttpGet]
public JsonResult GetHospitals()
{
    var hospitals = hospitalService.GetAllHospitals();
    return Json(hospitals, JsonRequestBehavior.AllowGet);
}

如前所述,我相信我會遇到解析器錯誤,因為我的某些數據包含撇號。 例如,“ Name可能包含字符串“ Women and Children's Hospital

我還是MVC / C#和Json的新手,所以我不確定如何解決這個問題。 有沒有一種方法可以擺脫所有撇號? 還是我應該做的其他事情。

讓我知道我說的話是否不清楚。 謝謝!

多虧了用戶戳,我才能夠解決此問題。 最終不是單引號引起的問題,而是我嘗試返回的JSON結果比MVC中默認設置的最大值長。

我可以使用此答案解決問題: 我可以在web.config中為maxJsonLength設置無限長度嗎?

您需要先使用str.Replace("'", "\\\\'")來轉義那些撇號。 "\\'"替換出現的"'" "\\'"

我認為問題與撇號無關,因為如果需要,json序列化程序應轉義它們。 無論如何,要更好地替換它們,請先序列化對象的集合。

[HttpGet]
public JsonResult GetHospitals()
{
    var hospitals = hospitalService.GetAllHospitals();

    // Replaces the apostrophes from the hospital name
    foreach(var hospital in hospitals) {
        hospital.Name = hospital.Name.Replace("'", ""); 
    }

    return Json(hospitals, JsonRequestBehavior.AllowGet);
}

這樣,將返回JSON,而名稱上沒有兩性。

您可以嘗試在撇號上使用html編碼,這會將它們轉換為'

通常,這是JSON.parse()調用或任何依賴於它的函數的問題,因為它不會轉義撇號或引號。 但是,對於HTML實體來說應該沒問題。

如果您習慣於使用eval()解析JSON,則不會看到它。 但是出於以下概述的原因,您實際上應該使用JSON解析器:

http://www.json.org/js.html

此處介紹了Microsoft的HTML編碼的ASP.NET實現。

https://msdn.microsoft.com/zh-CN/library/w3te6wfz(v=vs.110).aspx

暫無
暫無

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

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