Skip to content

Instantly share code, notes, and snippets.

@mrlacey
Created August 20, 2013 11:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrlacey/6280223 to your computer and use it in GitHub Desktop.
Save mrlacey/6280223 to your computer and use it in GitHub Desktop.
A comparison of how to serialize and deserialize objects to and from JSON with both Json.Net and ServiceStack.Text
namespace JsonSerialization
{
using System;
class Program
{
static void Main(string[] args)
{
var firstObject = new MyClass { Something = "a value", Anotherthing = "another value" };
Console.WriteLine("Here's an object");
Console.WriteLine(firstObject);
var jdn = Newtonsoft.Json.JsonConvert.SerializeObject(firstObject);
Console.WriteLine("Here's it serialized with JSON.Net");
Console.WriteLine(jdn);
var secondObject = Newtonsoft.Json.JsonConvert.DeserializeObject<MyClass>(jdn);
Console.WriteLine("Here's it deserialized with JSON.Net");
Console.WriteLine(secondObject);
Console.WriteLine("Here's the original object again");
Console.WriteLine(firstObject);
var sst = ServiceStack.Text.JsonSerializer.SerializeToString<MyClass>(firstObject);
Console.WriteLine("Here's it serialized with ServiceStack");
Console.WriteLine(sst);
var thirdObject = ServiceStack.Text.JsonSerializer.DeserializeFromString<MyClass>(sst);
Console.WriteLine("Here's it deserialized with ServiceStack");
Console.WriteLine(thirdObject);
Console.ReadKey(true);
}
}
class MyClass
{
public string Something { get; set; }
public string Anotherthing { get; set; }
public override string ToString()
{
return string.Format("MyClass: Something='{0}' AnotherThing='{1}'", this.Something, this.Anotherthing);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment