Skip to content

Instantly share code, notes, and snippets.

@forcewake
Created May 3, 2014 13:47

Revisions

  1. Scott V. Rosenthal renamed this gist Jul 12, 2011. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. Scott V. Rosenthal created this gist Jul 12, 2011.
    61 changes: 61 additions & 0 deletions JsonCoder
    Original 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();
    }
    }
    }