简体   繁体   English

返回带有引号的JsonResult

[英]Return JsonResult with apostrophes

As far as I can tell, I am getting a parser error because some of the data I am returning contains apostrophes. 据我所知,我收到解析器错误,因为我返回的某些数据包含撇号。

Error I'm getting: 我得到的错误:

SyntaxError: Unexpected end of input at Object.parse (native) at jQuery.parseJSON... SyntaxError:jQuery.parseJSON的Object.parse(本机)输入意外结束...

My javascript: 我的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
    }),
})

Controller JsonResult: 控制器JsonResult:

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

As I mentioned above, I believe I'm getting the parser error because some of my data contains apostrophes. 如前所述,我相信我会遇到解析器错误,因为我的某些数据包含撇号。 For example, Name might include the string Women and Children's Hospital 例如,“ Name可能包含字符串“ Women and Children's Hospital

I'm still new to MVC/C# and Json so I'm not sure how to go about solving this. 我还是MVC / C#和Json的新手,所以我不确定如何解决这个问题。 Is there a way to escape all of the apostrophes? 有没有一种方法可以摆脱所有撇号? Or is there something else I should be doing. 还是我应该做的其他事情。

Let me know if anything I said is not clear. 让我知道我说的话是否不清楚。 Thanks! 谢谢!

Thanks to the user poke I was able to resolve this issue. 多亏了用户戳,我才能够解决此问题。 It ended up not being a problem with the apostrophes but rather that the JSON Result that I was trying to return was longer than the max value set by default in MVC. 最终不是单引号引起的问题,而是我尝试返回的JSON结果比MVC中默认设置的最大值长。

I was able to use this answer to solve my problem: Can I set an unlimited length for maxJsonLength in web.config? 我可以使用此答案解决问题: 我可以在web.config中为maxJsonLength设置无限长度吗?

You need to escape those apostrophes first by using str.Replace("'", "\\\\'") . 您需要先使用str.Replace("'", "\\\\'")来转义那些撇号。 to replace occurrences of "'" with "\\'" "\\'"替换出现的"'" "\\'"

I don't thing that the problem is related to the apostrophes, because the json serializer should escape them if needed. 我认为问题与撇号无关,因为如果需要,json序列化程序应转义它们。 Anyway, to replace them better do it before serializing your object's collection. 无论如何,要更好地替换它们,请先序列化对象的集合。

[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);
}

In this way JSON will be returned without the aphostrophes on the name. 这样,将返回JSON,而名称上没有两性。

You could try using html encoding on the apostrophes, which should convert them to ' 您可以尝试在撇号上使用html编码,这会将它们转换为'

Usually this is a problem with the JSON.parse() call or any functions that rely on it, as it doesn't escape apostrophes or quotation marks. 通常,这是JSON.parse()调用或任何依赖于它的函数的问题,因为它不会转义撇号或引号。 It should be fine with HTML entities, however. 但是,对于HTML实体来说应该没问题。

If you're accustomed to using eval() to parse JSON, you won't have seen it. 如果您习惯于使用eval()解析JSON,则不会看到它。 But you should really use a JSON parser for reasons outlined here: 但是出于以下概述的原因,您实际上应该使用JSON解析器:

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

Microsoft's ASP.NET implementation of HTML Encoding is described here. 此处介绍了Microsoft的HTML编码的ASP.NET实现。

https://msdn.microsoft.com/en-us/library/w3te6wfz(v=vs.110).aspx 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