2016-10-26 386 views
0

我有我的購物車對象,我將其序列化爲將其扔入cookie中。這一切都很好。但是,當我去反序列化的另一邊我得到這個錯誤:如何在序列化JSON字符串之前轉義&符號

Newtonsoft.Json.JsonReaderException: Unterminated string. Expected delimiter: ". Path 'ShoppingCart[0].productName', line 1, position 221.

我已經確定誤差得到的符號字符拋出。

我連載的代碼如下所示:

string myObjectJson =JsonConvert.SerializeObject(cart); 

而且我反序列化代碼:

csm = JsonConvert.DeserializeObject<CartSummaryModel>(myCookie.Values[ "Cart" ]); 

我試圖把HttpUtility.HtmlEncodeJsonConvert前面,但並不做什麼,我希望它做。

這是我運行在其上的連載後滿弦:

{"ShoppingCart":[{"productIDs":[],"productNames":[],"productPrices":[],"productDescriptions":[],"imref":"24251","intDBQty":172,"isFrozen":false,"ProdId":"2063","productName":"Family Inspriration Gift Bags includes Tissue & Gift Tags, Set of 5","productPrice":14.0,"ProductDesc":"\"A Special Gift, for a Special Someone!\" These inspirational gift bags are ideal for wrapping small to medium-sized gifts. Includes white tissue, gift tags, and secure cord handles. 8\"L x 4 3/4\"W x 10 1/2\"H. Set of 5","productQuantity":1}],"TotalQty":1,"SubTotalCost":14.0,"TotalCost":22.0,"TotalDiscount":0.0,"ReferralCode":"","ReferralEmail":"","TotalShipping":8.0,"FreeShipMin":70.0,"TotalProcessing":0.0,"ShipText":"Est. Ship","TotalTax":0.0,"TaxText":"Est. Tax","OERef":"","CartNum":"","Message":"","LowQuantity":false,"HasFrozen":false}

+0

「未終止的字符串」之後?這與'&'...無關&''&'不是JS metachar,並且不需要轉義。 '「&」'是一個完整/有效的JSON字符串。 –

回答

3

你的對象轉換成JSON字符串使用 HttpUtility.UrlEncode(myObjectJson)和反序列化時使用HttpUtility.UrlDecode(myCookie.Values["Cart"])

+0

那個伎倆,謝謝! – dmikester1