FANDOM


Add reference System.Runtime.Serialization.

using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
using System.Runtime.Serialization;

public static class JSONSerializer<TType> where TType : class
{
    /// <summary>
    /// Serializes an object to JSON
    /// </summary>
    public static string Serialize(TType instance)
    {
        var serializer = new DataContractJsonSerializer(typeof(TType));
        using (var stream = new MemoryStream())
        {
            serializer.WriteObject(stream, instance);
            return Encoding.Default.GetString(stream.ToArray());
        }
    }

    /// <summary>
    /// DeSerializes an object from JSON
    /// </summary>
    public static TType DeSerialize(string json)
    {
        using (var stream = new MemoryStream(Encoding.Default.GetBytes(json)))
        {
            var serializer = new DataContractJsonSerializer(typeof(TType));
            return serializer.ReadObject(stream) as TType;
        }
    }
}

Example class

[DataContract]
public class MusicInfo
{
    [DataMember]
    public string Artist { get; set; }

    [DataMember]
    public string[] Genres { get; set; }

    [DataMember]
    public int Year { get; set; }    
}

Instantiate the class:


            var musicInfo = new MusicInfo
            {
                 Artist = "Metallica",
                 Genres = new string[] { "Rock", "Metal" },
                 Year = 2012
            };

Write it to a file


            var serialized = JSONSerializer<MusicInfo>.Serialize(musicInfo);

            File.WriteAllText(@"e:\temp\x.txt", serialized);

Read it from a file


            var r = File.ReadAllText(@"e:\temp\x.txt");

            var deserialized = JSONSerializer<MusicInfo>.DeSerialize(r);

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.