Can JavaScriptSerializer exclude properties with null/default values?

FYI, if you’d like to go with the easier solution, here’s what I used to accomplish this using a JavaScriptConverter implementation with the JavaScriptSerializer: private class NullPropertiesConverter: JavaScriptConverter { public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) { throw new NotImplementedException(); } public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) { var jsonExample …

Read more

JavaScriptSerializer.Deserialize – how to change field names

I took another try at it, using the DataContractJsonSerializer class. This solves it: The code looks like this: using System.Runtime.Serialization; [DataContract] public class DataObject { [DataMember(Name = “user_id”)] public int UserId { get; set; } [DataMember(Name = “detail_level”)] public string DetailLevel { get; set; } } And the test is: using System.Runtime.Serialization.Json; [TestMethod] public void …

Read more

How do I get formatted JSON in .NET using C#?

You are going to have a hard time accomplishing this with JavaScriptSerializer. Try JSON.Net. With minor modifications from JSON.Net example using System; using Newtonsoft.Json; namespace JsonPrettyPrint { internal class Program { private static void Main(string[] args) { Product product = new Product { Name = “Apple”, Expiry = new DateTime(2008, 12, 28), Price = 3.99M, …

Read more

JavaScriptSerializer – JSON serialization of enum as string

I have found that Json.NET provides the exact functionality I’m looking for with a StringEnumConverter attribute: using Newtonsoft.Json; using Newtonsoft.Json.Converters; [JsonConverter(typeof(StringEnumConverter))] public Gender Gender { get; set; } More details at available on StringEnumConverter documentation. There are other places to configure this converter more globally: enum itself if you want enum always be serialized/deserialized as …

Read more