Created
May 3, 2014 13:47
Revisions
-
Scott V. Rosenthal renamed this gist
Jul 12, 2011 . 1 changed file with 0 additions and 0 deletions.There are no files selected for viewing
File renamed without changes. -
Scott V. Rosenthal created this gist
Jul 12, 2011 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,61 @@ using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization.Json; using System.Text; namespace Test.Lib { /// <summary> /// Generic type class for json load/dump, can be persisted to file/database /// Easier to manipulate in the file/database than xml, etc... /// Useful for app config settings and the like /// /// Example of class that would be persisted to a column in the database /// using System; /// using System.Runtime.Serialization; /// /// namespace Test.Models /// { /// [DataContract] /// public class ConfigKeyValue /// { /// [DataMember] /// internal string name; /// /// [DataMember] /// internal string value; /// } /// } /// /// var rows = new List<ConfigKeyValue>(); /// var json = JsonCoder<List<ConfigKeyValue>>.Dump(rows); /// var rowsLoad = JsonCoder<List<ConfigKeyValue>>.Load(json); /// </summary> /// <typeparam name="T"></typeparam> public static class JsonCoder<T> { public static T Load(string json) { byte[] byteArray = Encoding.UTF8.GetBytes(json); var stream = new MemoryStream(byteArray); var ser = new DataContractJsonSerializer(typeof(T)); return (T)ser.ReadObject(stream); } public static string Dump(T instance) { var stream = new MemoryStream(); var ser = new DataContractJsonSerializer(typeof(T)); ser.WriteObject(stream, instance); stream.Position = 0; var reader = new StreamReader(stream); return reader.ReadToEnd(); } } }