Json.NET is a popular high-performance JSON framework for .NET
Features
- Flexible JSON serializer for converting between .NET objects and JSON
- LINQ to JSON for manually reading and writing JSON
- High performance, faster than .NET’s built-in JSON serializers
- Write indented, easy to read JSON
- Convert JSON to and from XML
- Supports .NET 2, .NET 3.5, .NET 4, Silverlight, Windows Phone and Windows 8 Metro
Serialization Wrapper
The following is a wrapper I wrote to wrap boiler plate code and facilitate reuse.
public sealed class SerializerWrapper { readonly JsonSerializer serializer = new JsonSerializer(); public void Serialize(Stream ms, object obj) { var jsonTextWriter = new JsonTextWriter(new StreamWriter(ms)); serializer.Serialize(jsonTextWriter,obj); jsonTextWriter.Flush(); ms.Position = 0; } public TType Deserialize<TType>(Stream ms) { var jsonTextReader = new JsonTextReader(new StreamReader(ms)); return serializer.Deserialize<TType>(jsonTextReader); } }
Using the SerializationWrapper
[TestClass] public class SerializationWrapperUnitTest { public class TestObject { public string Message { get; set; } public string By { get; set; } } [TestMethod] public void SerializeObject() { var obj = new TestObject { By = "Alexandre Brisebois", Message = "This is a test Message" }; var s = new SerializationWrapper(); string serializedObject; using(var ms = new MemoryStream()) { s.Serialize(ms, obj); TextReader reader = new StreamReader(ms); serializedObject = reader.ReadToEnd(); } Debug.WriteLine(serializedObject); Assert.IsFalse(string.IsNullOrWhiteSpace(serializedObject)); } }
Resulting JSON Object
{"Message":"This is a test Message","By":"Alexandre Brisebois"}
How do you deal with special characters? Is there a library to reference when deserializing? Suppose in your example there are an extra pair of double-quotes like so, {“Message”:”This is a “test” Message”,”By”:”Alexandre Brisebois”}, could you deserialize it without writing a method to add back-slashes to it.
I really do like your example though, especially the way you include your testing method!
Thank you very much.
LikeLike
You would have to test it out, but my guess is that you would need to escape the quotes.
LikeLike