Home / Blog / Documentation / Code Generator / Settings / Serialization / JSon Serialization
The code generated for Serializer/Deserializer functions uses JSon.Net Serializers from NewtonSoft. Detailed documentation is available on the official NewtonSoft website.
xsd2code++ allows to configure the serializer on the setting that is the most relevant. Those can evolve over time with the addition of additional parameters. These parameters are detailed in this document.
The first thing to do is to enable the generation of serialization methods like this :
Serialization→Enable = true
Serialization→DefaultSerialiser = JSonSerializer
This is enough to produce a JSON file or stream from the generated classes.
#region Serialize/Deserialize /// <summary> /// Serializes current PurchaseOrderType object into an json string /// </summary> public virtual string Serialize() { Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings(); return JsonConvert.SerializeObject(this, settings); } /// <summary> /// Deserializes PurchaseOrderType object /// </summary> /// <param name="input">string workflow markup to deserialize</param> /// <param name="obj">Output PurchaseOrderType object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this Serializer can deserialize the object; otherwise, false</returns> public static bool Deserialize(string input, out PurchaseOrderType obj, out System.Exception exception) { exception = null; obj = default(PurchaseOrderType); try { obj = Deserialize(input); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool Deserialize(string input, out PurchaseOrderType obj) { System.Exception exception = null; return Deserialize(input, out obj, out exception); } public static PurchaseOrderType Deserialize(string input) { Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings(); return JsonConvert.DeserializeObject<PurchaseOrderType>(input, settings); } #endregion public virtual void SaveToFile(string fileName) { System.IO.StreamWriter streamWriter = null; try { string xmlString = Serialize(); System.IO.FileInfo outputFile = new System.IO.FileInfo(fileName); streamWriter = outputFile.CreateText(); streamWriter.WriteLine(xmlString); streamWriter.Close(); } finally { if ((streamWriter != null)) { streamWriter.Dispose(); } } } public static PurchaseOrderType LoadFromFile(string fileName) { System.IO.FileStream file = null; System.IO.StreamReader sr = null; try { file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read); sr = new System.IO.StreamReader(file); string xmlString = sr.ReadToEnd(); sr.Close(); file.Close(); return Deserialize(xmlString); } finally { if ((file != null)) { file.Dispose(); } if ((sr != null)) { sr.Dispose(); } } } }
Each of your classes will contain the serialization & deserialization methods. However, it is possible to group everything in a base class. To do so, the option below must be activated
GenericBaseClass → Enable = true
By default the generated methods are : LoadFromFile(...), SaveToFile(...), Serialize(...), Deserialize(...)
Here is an example :
static void Main(string[] args) { Console.WriteLine("Basic JSON Serialization based on propertyName"); PurchaseOrderType po = new PurchaseOrderType(); po.BillTo.name = "Kaila Tamara"; po.BillTo.street = "3490 Green Hill Road"; po.BillTo.zip = "72761"; po.OrderDate = DateTime.Now; // Save data to json file po.SaveToFile("c:\\temp\\po.json"); // Save json data to string var jsonValue = po.Serialize(); // Load Data from file var poFromFile = PurchaseOrderType.LoadFromFile("c:\\temp\\po.json"); // Load data from string var poFromString = PurchaseOrderType.Deserialize(jsonValue); }
DateFormatHandedling, DateFormatString, DateParseHandedling, DateTimeZoneHandling, DefaultValueHandling, FloatFormatHandling, FloatParseHandling, MissingMemberHandling, NullValueHandling, StringEscapeHandling
All these parameters are those of the JSON serializer itself. The official documentation is available on the author's website.
For copyright reasons this documentation is not included here but only illustrated with examples.
DateFormatHandling controls how dates are serialized. you have two possibilities :
IsoDateFormat
: writes dates in the ISO 8601 format, e.g. "2012-03-21T05:40Z"
.
MicrosoftDateFormat
: Dates are written in the Microsoft JSON format, e.g. "\/Date(1198908717056)\/"
.
This option defines the date format that will be used in the Json file
The default date format is ISO 8601
But if by exemple the format "dd MM, yyyyy" is specified the result will be :
MissingMemberHandling controls how missing members, e.g. JSON contains a property that isn't a member on the object, are handled during deserialization.
Ignore, By default Json.NET ignores JSON if there is no field or property for its value to be set to during deserialization.
Error, son.NET errors when there is a missing member during deserialization.
NullValueHandling controls how null values on .NET objects are handled during serialization and how null values in JSON are handled during deserialization.
Include : writes null values to JSON when serializing and sets null values to fields/properties when deserializing
Ignore : skip writing JSON null properties
NullValueHandling can also be customized on individual properties with JsonPropertyAttribute.
DefaultValueHandling controls how Json.NET uses default values set using the .NET DefaultValueAttribute when serializing and deserializing.
Include, will write a field/property value to JSON when serializing if the value is the same as the field/property's default value.
Ignore, will skip writing a field/property value to JSON if the value is the same as the field/property's default value, or the custom value specified in DefaultValueAttribute if the attribute is present. The Json.NET deserializer will skip setting a .NET object's field/property if the JSON value is the same as the default value.
The example below illustrates the resulting JSON value:
PurchaseOrderType po = new PurchaseOrderType(); po.BillTo.city = "New York"; po.OrderDate = DateTime.Now.ToString(); po.ShipTo = null; // Save data to json filepo.SaveToFile("c:\\temp\\po.json");