C# Json Serialzer

These two methods are tool methods, they are very useful. Below code's demo is about object array serialisation. So theGetknowTypes method is used in the constructor of the class namedDataContractJsonSerializer

The project demo the serialisation of object.

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


namespace ExampleSerialize
{
    class Program
    {
        static void Main(string[] args)
        {
            object[] obj1 = new[] { "1", "2", "3" };

            string value = SerializeObject<object[]>(obj1);

            Console.WriteLine("Object string: "+value);

            object[] obj2 = DeserializeString<object[]>(value);

            Console.WriteLine("Object: "+obj2);

            object[] obj3 = new[] { new A() };

            ((A)DeserializeString<object[]>(SerializeObject<object[]>(obj3))[0]).Speak();

            Console.ReadLine();
        }

        private static string SerializeObject<T>(T data)
        {
            string serializeString = null;

            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(object), GetknowTypes(null));

            MemoryStream str = new MemoryStream();

            serializer.WriteObject(str,data);

            byte[] buffer = new byte[str.Length];

            str.Seek(0,SeekOrigin.Begin);

            str.Read(buffer,0,(int)str.Length);

            serializeString = Encoding.UTF8.GetString(buffer, 0, buffer.Length);

            return serializeString;
        }

        private static T DeserializeString<T>(string dataString)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(object),GetknowTypes(null));

            MemoryStream str = new MemoryStream();

            byte[] buffer = Encoding.UTF8.GetBytes(dataString);

            str.Write(buffer,0,buffer.Length);

            str.Seek(0,SeekOrigin.Begin);

            T result = (T)serializer.ReadObject(str);

            return result;
        }

        private static IEnumerable<Type> GetknowTypes(object provider)
        {
            yield return typeof(object[]);
            yield return typeof(string[]);
            yield return typeof(A);
            yield return typeof(A[]);
        }
    }

    public class A
    {
        public string Name { get; set; }
        public string Words { get; set; }

        public A()
        {
            this.Name = "A";
            this.Words = "I am A";
        }

        public A(string name, string words)
        {
            this.Name = name;
            this.Words = words;
        }

        public void Speak()
        {
            Console.WriteLine(this.Name+": "+this.Words);
        }
    }
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章