Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.net Serialize C# object to JSON Issue

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!

like image 494
MetRay Avatar asked Feb 17 '12 15:02

MetRay


People also ask

What is JSON serialization in C#?

Serialization is the process of converting . NET objects such as strings into a JSON format and deserialization is the process of converting JSON data into . NET objects. In this article and code examples, first we will learn how to serialize JSON in C# and then we will learn how to deserialize JSON in C#.

Is JSON net the same as Newtonsoft?

Thanks. Json.NET vs Newtonsoft. Json are the same thing. You must be trying to use the same code with different versions of Json.NET.

How do I deserialize JSON in .NET core?

NET objects (deserialize) A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.


1 Answers

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))" }; 
like image 192
jrummell Avatar answered Sep 28 '22 17:09

jrummell