Created
August 20, 2013 11:24
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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