This article describes how to exploit the JSON serialization through the classes generated by xsd2code+. |
The code generated for Serializer/Deserializer uses JSon.Net from NewtonSoft. Detailed documentation is available on the official website https://www.newtonsoft.com/.
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 after 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 to produce a JSON file from a generated class.
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); } |
All these parameters are those of the JSON serializer itself. The official documentation is available on the author's website.
https://www.newtonsoft.com/json/help/html/SerializationSettings.htm
For copyright reasons this documentation is not included here but only illustrated with examples.
DateFormatHandling controls how dates are serialized. Deux possibilités,
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)\/".
Ce paramètre permet de définir le format de date qui sera produit dans le fichier JSON
Par defaut la date est au format ISO 8601
{"ShipTo":[],"BillTo": "OrderDate":"2020-04-20T19:38:49.1119852+02:00"} |
But if by exemple the format "d MMMM, yyyyy" is specified the result will be :
{"ShipTo":[],"BillTo": "OrderDate":"20 April, 2020"} |
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
{ "ShipTo": null, "BillTo": { "name": "Kaila Tamara", "street": "3490 Green Hill Road", "city": null, "state": null, "zip": "72761", "country": "US" }, "OrderDate": "2020-04-20T19:53:16.1639456+02:00" } |
Ignore : skip writing JSON null properties
{ "BillTo": { "name": "Kaila Tamara", "street": "3490 Green Hill Road", "zip": "72761", "country": "US" }, "OrderDate": "2020-04-20T19:46:37.0493786+02:00" } |
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.
DefaultValueHandling option is very interesting because it allows to reduce the size of the JSON. In other words, if the value corresponds to the default value, it will not be serialized if the Ignore option is chosen. Cela fonctionne pour les chaine de caractère vide, les valeur numérique à 0 etc. Mais cela fonctionne aussi If your Schema defines elements containing the default attribute as shown in the example below, an equivalent attribute will be generated on the properties. |
"city": { "description": "Defined the country of delivery or billing", "type": "string", "minLength": 5, "maxLength": 40, "default": "New York" }, |
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 file po.SaveToFile(@"c:\temp\po.json"); |
Include
| Ignore
|
---|