简体   繁体   中英

How to escape ampersand before serializing JSON string

I have my cart object that I am serializing to throw it into a cookie. That all works fine. But when I go to deserialize it on the other side I get this error:

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

I have determined that the error is getting thrown on the ampersand character.

My serialize code looks like this:

 string myObjectJson =JsonConvert.SerializeObject( cart );

And my deserialize code:

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

I have tried putting HttpUtility.HtmlEncode in front of JsonConvert but that doesn't do what I want it to do.

Here is my full string after running the serialize on it:

{"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}

将您的对象转换为JSON字符串后,请使用HttpUtility.UrlEncode(myObjectJson) ,反序列化时请使用HttpUtility.UrlDecode(myCookie.Values["Cart"])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM