September 4, 2015

Using Newtonsoft (Open Source) JSON Serializer

Here is how to serialize and deserialize a JSON object to and from a string
string json = JsonConvert.SerializeObject(target, Formatting.Indented); // Serialize to a string
var reconstituted = JsonConvert.DeserializeObject<ClassOfTarget>(json); // Deserialize from a string
Documentation is here: http://www.newtonsoft.com/json/help/html/Introduction.htm

Can use with attributes:
[DataContract] // ONLY 'marked' properties are serialized in this case
public class ClassOfTarget
{
...
[DataMember] // Use this attribute to 'mark' a property
public Dictionary<string, string> Mappings { get; set; }
...
}
Newtonsoft JSON serializer will recognise these Microsoft attributes and they also have a few of their own they will recognise as well.

Serializing/Deserializing to a file using some extension methods
using Newtonsoft.Json;

public static class JsonExtensions
{

  public static void WriteToJsonFile<T>(
    this T objectToWrite, 
    string filePath
    // This next parameter is optional but ensures that 
    // when you have types mixed with their derived types
    // they can be serialized as well
    bool derivedTypesPresent = false) 
      where T : new()
  {
    FileInfo file = new FileInfo(filePath);
    Debug.Assert(!file.Exists);
    try
    {
      // Serialize JSON directly to a file
      using (StreamWriter sw = new StreamWriter(file.FullName))
      {
        using (JsonWriter writer = new JsonTextWriter(sw))
        {
          JsonSerializer serializer = new JsonSerializer();
          serializer.Formatting = Formatting.Indented;
          if (derivedTypesPresent) // Store type info in JSON
            serializer.TypeNameHandling = TypeNameHandling.All; 

          // target is the object you want serialized
          serializer.Serialize(writer, objectToWrite); 
        }
      }
    }
    catch (JsonSerializationException ex)
    {
        Trace.WriteLine($"Json Serialization Exception occurred: {ex}");
    }
  }

  public static T ReadFromJsonFile<T>(
    this string filePath
    // This next parameter is optional but ensures that 
    // when you have types mixed with their derived types
    // they can be serialized as well
    bool derivedTypesPresent = false)
      where T : class, new()
  {
    FileInfo file = new FileInfo(filePath);
    Debug.Assert(file.Exists);
    T reconstituted = null;

    try
    {
      // deserialize JSON directly from a file
      using (var reader = file.OpenText())
      {
        var serializer = new JsonSerializer();
        if (derivedTypesPresent) // Store type info in JSON
          serializer.TypeNameHandling = TypeNameHandling.All; 
        reconstituted = (T)serializer.Deserialize(reader, typeof(T));
      }
    }
    catch (JsonSerializationException ex)
    {
        Trace.WriteLine($"Json Serialization Exception occurred: {ex}");
    }
    return reconstituted;
  }
  
  public static string WriteToJsonString<T>(
    this T objectToWrite,
    //This parameter is optional but ensures that 
    //when you have types mixed with their derived types
    // they can be serialized as well
    bool derivedTypesPresent = false)
    where T : new()
  {
    string json = "";
    Debug.Assert(objectToWrite != null);
    try
    {
        var serializerSettings = new JsonSerializerSettings();
        serializerSettings.DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate;
        if (derivedTypesPresent) // Then store type info in JSON as well
            serializerSettings.TypeNameHandling = TypeNameHandling.All;

        // Serialize to a string  
        json = JsonConvert.SerializeObject(objectToWrite, Formatting.None); 
    }
    catch (JsonSerializationException ex)
    {
        Trace.WriteLine($"Json Serialization Exception occurred: {ex}");
    }
    return json.ToString();
  }

  public static T ReadFromJsonString<T>(
    this string json,
    bool derivedTypesPresent = false)
    where T : class, new()
  {
    Debug.Assert(!string.IsNullOrWhiteSpace(json));
    T reconstituted = null;

    try
    {
        var serializerSettings = new JsonSerializerSettings();
        serializerSettings.DefaultValueHandling = DefaultValueHandling.
            IgnoreAndPopulate;
        if (derivedTypesPresent) // Then store type info in JSON as well
            serializerSettings.TypeNameHandling = TypeNameHandling.All;

        reconstituted = JsonConvert.DeserializeObject<T>(json, 
            serializerSettings);
    }
    catch (JsonSerializationException ex)
    {
        Trace.WriteLine($"Json Serialization Exception occurred: {ex}");
    }
    return reconstituted;
  }

}
And to serialise and deserialise to and from a file:
StarSystem myObject = new StarSystem(...);
// To write an object to a json file
myObject.WriteToJsonFile<StarSystem>(filePath);
// To read an object from a jsonfile
myObject = filePath.ReadFromJsonFile<StarSystem>(); 
And to serialise and deserialise to and from a string:
StarSystem myObject = new StarSystem(...);
// To write an object to a json string
string json = myObject.WriteToJsonString<StarSystem>();
// To read an object from a json string
myObject = json.ReadFromJsonString<StarSystem>(); 
To convert the JSON to XML, use the JSON string like so
// To convert the JSON to XML
string json = ....
XNode node = JsonConvert.DeserializeXNode(json, "Title");
string xml = node.ToString();

No comments: