dmikester1 dmikester1 - 10 months ago 96
C# Question

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
in front of
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}

Answer Source

After converting your object to JSON string use HttpUtility.UrlEncode(myObjectJson) and when deserializing use HttpUtility.UrlDecode(myCookie.Values["Cart"])