About
In this code snippet, we will learn about JSON serialization in C#.
Serialization is when you take an object and convert it to a stream of bytes that can be then stored in a file, database or memory. This is useful if you want to store the state of your objects or send them over the network(for example an API). Of course, you can also deserialize a file/database entry back into an object.
Note: See also XML and binary serialization.
In this example, we will serialize and deserialize an object to/from JSON. I will only make a JSON string. To make a JSON file you simply write the string to the file like you would for any other text. At the end just make sure to save the file with the .json extension instead of .txt.
Additionally, we’ll see how we can create our own contract resolver with which we can define how the mapping from object to JSON and vice versa is performed. For example, we can set a specific property of an object to get serialized as text instead of a number or we can change the name of a property when serialized/deserialized, etc.
Update: Since this post was written Microsoft added JSON serialization/deserialization as part of .NET(System.Text.Json namespace), consider checking it out here.
Let’s have a look at the code below to see how to perform JSON serialization.
Code:
using System; //Add this. (Use NuGet to install Newtonsoft library) using Newtonsoft.Json; namespace JSONSerialization { class Program { static void Main(string[] args) { //The object that will be serialized/deserialized. MyClass MC = new MyClass(5, "Hi!"); //Serialize to JSON.//////////////////////////////////////////////// string json = JsonConvert.SerializeObject(MC); Console.WriteLine("JSON: " + json); Console.WriteLine(); //Deserialize from JSON./////////////////////////////////////////// MyClass MCDeserializedFromJSON = JsonConvert.DeserializeObject<MyClass>(json); Console.WriteLine("MyFirstProperty: " + MCDeserializedFromJSON.MyFirstProperty + " MySecondProperty: " + MCDeserializedFromJSON.MySecondProperty); Console.ReadLine(); } } //Make sure the class that will be serialized is public. //Also all the members of the class that will be serialized must be public. public class MyClass { public int MyFirstProperty { get; set; } public string MySecondProperty { get; set; } public MyClass() { } public MyClass(int a, string b) { MyFirstProperty = a; MySecondProperty = b; } } }
Resulting output:
Custom Contract Resolver Code:
using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System.Reflection; namespace JSONSerialization { class Program { static void Main(string[] args) { //The object that will be serialized/deserialized. MyClass MC = new MyClass(5, "Hi!"); //Serialize to JSON.//////////////////////////////////////////////// //Here we can set the JsonSerializerSettings to use our own custom contract resolver instead of the default one. var settings = new JsonSerializerSettings { ContractResolver = new CustomContractResolver(), /*Here you can set other settings like formatting, what to do with null values, etc. Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Populate, MissingMemberHandling = MissingMemberHandling.Ignore */ }; string json = JsonConvert.SerializeObject(MC, settings); Console.WriteLine("JSON: " + json); Console.WriteLine(); } } //Make sure the class that will be serialized is public. //Also all the members of the class that will be serialized must be public. public class MyClass { public int MyFirstProperty { get; set; } public string MySecondProperty { get; set; } public MyClass() { } public MyClass(int a, string b) { MyFirstProperty = a; MySecondProperty = b; } } //Here we define our custom contract resolver. public class CustomContractResolver : DefaultContractResolver { protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) { //We'll do something silly like renaming MySecondProperty to MyThirdProperty. //But you get the idea, you can do whatever you want. JsonProperty property = base.CreateProperty(member, memberSerialization); if (property.PropertyName == "MySecondProperty") { property.PropertyName = "MyThirdProperty"; } return property; } //Or you can just override the property name resolver like so: /*protected override string ResolvePropertyName(string name) { if (name == "MySecondProperty") return "MyThirdProperty"; else return name; }*/ } }