Serialise and deserialise with JSON

Serialising allows objects to be converted to strings and then back. This is especially useful when dealing with sending complex objects over the wire. JSON has become the go to standard..

JSON Convert is a simple way of serialising objects to strings..


// My Class I want to serialise
MyClass myClass = new MyClass();

// Serialised
string output = JsonConvert.SerializeObject(myClass);

// And getting it back again
MyClass deserialized = JsonConvert.DeserializeObject(output);

Or you may need a more complex method using JSON Serialiser.


MyClass myClass = new MyClass();
myClass.MyDate = new DateTime.Now;
JsonSerializer serialiser = new JsonSerializer();
serialiser.Converters.Add(new JavaScriptDateTimeConverter());
serialiser.NullValueHandling = NullValueHandling.Ignore;
 
StreamWriter stream = new StreamWriter(@"c:\mytextfile.txt")
JsonWriter writer = new JsonTextWriter(stream)
using (writer)
{
    serialiser.Serialize(writer, myClass);
}

Leave a Reply

Your email address will not be published. Required fields are marked *