我遇到了一些情況,使用Json.NET將一些對象序列化爲JSON,然後註冊爲客戶端腳本塊。該對象的JSON被投入的JavaScript在一個單引號的文字有點像這樣:C# - 無法爲JSON轉義撇號
// javascript output, normal
reportParameters = '{ "Location" : "My house" }';
但有時它需要投入包含撇號的值,比如「比利之家」,所以很明顯,我將需要逃避這一點,否則JavaScript的休息。
// javascript output scenario, bad
reportParameters = '{ "Location" : "Billy's House" }';
// what I need is this
reportParameters = '{ "Location" : "Billy\'s House" }';
我試着這樣做:
// C# input
reportParameterText = reportParameterText.Replace("'", @"\'");`
然而,這總是它更改爲「比利\\之家」,我不知道爲什麼。許多人們遇到類似問題的地方都會說「這只是調試器代表一個反斜槓的方式」,但在我的情況下,我仍然有2個反斜槓進入javascript,因此反斜槓會被轉義,而不是撇號和所有內容休息。
// javascript actual output, bad
reportParameters = '{ "Location" : "Billy\\'s House" }';
我跟着它通過調試,和它之前,它被序列化後有兩個反斜槓,所以序列化是沒有問題的。正如我之前所說的,它絕對不僅僅是調試器對轉義字符的表示,因爲這些值會將其轉換爲源代碼。
其他的解決方案我試過,所有的C#:
reportParameterText = reportParameterText.Replace("'", "\'"); // No change
reportParameterText = reportParameterText.Replace("'", "\\'"); // Creates 2 backslashes
reportParameterText = reportParameterText.Replace("'", @"[%]");
reportParameterText = reportParameterText.Replace(@"[%]", @"\'"); // Creates 2 backslashes
問題:爲什麼我總是得到2個反斜線,我怎麼能保證我只放下了嗎?
這是.NET 4
SOLUTION
感謝您的幫助和信息,大家好。我通過結合幾個人的建議並基本上做了@ Ali123的建議來解決我的問題。至於C#中「第二個反斜槓來自哪裏」的問題,它與@Gusman的答案如下。
我在C#中的序列化字符串在JavaScript中不是安全的字符串,但它仍然是格式正確的JSON。任何東西的JS黑盒子都接受一個JSON對象的字符串,這個JSON對象留在reportParameters
變量中,但這並不意味着我必須在C#中獲得字符串化的JSON。
因此,而不是在與string.replace C#,我已經準備生成的JS代碼看起來像這樣:
var tempThing = { "Location" : "Billy's House" };
reportParameters = JSON.stringify(tempThing);
StartDoingThings();
再次看它,我可以削減線路輸出的是,但它仍然作品。
TL; DR謝謝,我知道這是一個有點混亂的問題。
JSON什麼你使用它無法處理撇號串行?嘗試Json.NET,我很確定它做的事情是正確的。 –
@SamAxe它是Json.NET。將添加到帖子。 –
看到這個問題:https://stackoverflow.com/questions/1242118/how-to-escape-json-string – frodo2975