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 to a file
// Serialize JSON directly to a file
using (StreamWriter sw = new StreamWriter(filePath))
{
 using (JsonWriter writer = new JsonTextWriter(sw))
 {
  JsonSerializer serializer = new JsonSerializer();
  serializer.Formatting = Formatting.Indented;
  // This next line is optional but ensures that 
  // when you have types mixed with their derived types
  // they can be deserialized as well
  // but it is needed in the deserialize part as well!
  serializer.TypeNameHandling = TypeNameHandling.All; // Store type info in JSON

  serializer.Serialize(writer, target); // target is the object you want serialized
 }
}
Deserializing from a file
ClassOfTarget reconstituted = null;

// deserialize JSON directly from a file
using (StreamReader file = File.OpenText(filePath))
{
 var serializer = new JsonSerializer();
  // This next line is optional but ensures that 
  // when you have types mixed with their derived types
  // they can be deserialized as well
  serializer.TypeNameHandling = TypeNameHandling.All; // Store type info in JSON
 reconstituted = (ClassOfTarget)serializer.Deserialize(file, typeof(ClassOfTarget));
}
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: