Skip to content

Instantly share code, notes, and snippets.

@forcewake
Created May 3, 2014 13:47
Show Gist options
  • Save forcewake/3b0516e0cde3dc48bccb to your computer and use it in GitHub Desktop.
Save forcewake/3b0516e0cde3dc48bccb to your computer and use it in GitHub Desktop.
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();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment