42

I am trying to serialize a C# object to JSON using JSON.net library. The issue I am having is the string being created has &quot's in it.

Below is the string returned via JsonConvert.SerializeObject:

{
    "ComId": "AAAiB+AAHAALOaFAAL",
    "CovId": "AAABC9AAPAAAZYUAAI",
    "EffectiveDate": "\\/Date(1329368400000-0500)\\/",
    "ExpirationDate": "\\/Date(1360990800000-0500)\\/",
    "State": "TX",
    "DeductibleAmount": 500.0,
    "DeductibleType": "PD"
}

Running the string through JSONLint returns:

Parse error on line 1:
{    "ComId": &
-----^
Expecting 'STRING', '}'

Below is the object I am trying to serialize into JSON:

public class CommonInfoModel
{
    public virtual string ComId { get; set; }
    public virtual string CovId { get; set; }

    [Display(Name = "Effective Date")]
    public virtual DateTime EffectiveDate { get; set; }

    [Display(Name = "Expiration Date")]
    public virtual DateTime ExpirationDate { get; set; }

    [Display(Name = "State")]
    public virtual string State { get; set; }

    [Display(Name = "Deductible Amount")]
    public virtual decimal DeductibleAmount { get; set; }

    [Display(Name = "Deductible Type")]
    public virtual string DeductibleType { get; set; }
}

Am I doing something wrong? I have searched and it seems others who use the method get cleaner strings! Thank you for your time in advance!

MetRay
  • 423
  • 1
  • 4
  • 7
  • Why don't you make a replace of that " from " and then parse it – jcvegan Feb 17 '12 at 15:43
  • 1
    How are you using JSON? Are you returning it from a Controller Action? Have you tried `return Json(model);`? – jrummell Feb 17 '12 at 15:44
  • This is `{"ComId":null, "CovId":null,"EffectiveDate":"\/Date(-62135596800000+0200)\/", "ExpirationDate":"\/Date(-62135596800000+0200)\/", "State":null, "DeductibleAmount":0.0,"DeductibleType":null}` what I get when I run **`JsonConvert.SerializeObject(new CommonInfoModel())`**. You must be doing something with your string after serialization – L.B Feb 17 '12 at 15:47
  • do you have method like SerializeObject(Object, Formatting, JsonSerializerSettings) so you could handle the formatting/setting ? – Turbot Feb 17 '12 at 16:01
  • @jrummell This is a dry run I am working on, but I am trying to convert a MVC Model to a JSON object and passing it via JQuery. ie $.ajax({ data: { json : "@JsonConvert.SerializeObject(Model)" } .... – MetRay Feb 17 '12 at 16:05

1 Answers1

114

Your json string is being HTML encoded. Since you're rendering the json in your view, you can use the @Html.Raw() helper to prevent it from being encoded.

var data = { json : "@Html.Raw(JsonConvert.SerializeObject(Model))" };
jrummell
  • 42,637
  • 17
  • 112
  • 171