2015年3月7日土曜日

objectーjsonの相互変換 convert Json To object, object To Json

コピペして実装するだけOK。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Globalization;
using System.Xml;

//System.Runtime.Serialization参照追加
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var model0 = new TicketModel()
            {
                From = "Tokyo",
                To = "Sinjuku",
                ID = 1,
                IsUse = true,
                IsExit = false,
            };

            var json = JSonConvert.ToJSon(model0);
            var model1 = JSonConvert.ToModel(json);
            Console.WriteLine(json);
            Console.WriteLine(model0.GetDateTime().ToString());
            Console.WriteLine(model1.GetDateTime().ToString());
            Console.ReadLine();
        }

    }

    public static class JSonConvert
    {
        public static T ToModel(string jsonString)
        {
            var serializer = new DataContractJsonSerializer(typeof(T));
            var jsonBytes = Encoding.UTF8.GetBytes(jsonString);
            using (var ms = new MemoryStream(jsonBytes))
            {
                return (T)serializer.ReadObject(ms);
            }
        }

        public static string ToJSon(T model)
        {
            var serializer = new DataContractJsonSerializer(typeof(T));
            using (var ms = new MemoryStream())
            {
                serializer.WriteObject(ms, model);
                return Encoding.UTF8.GetString(ms.ToArray());
            }
        }
    }

    public static class DateConvert
    {
        private static readonly string UtcDateFormat = "s";
        private static readonly string UtcDateFooter = "Z";

        public static DateTime ToDate(string utc)
        {
            return DateTime.Parse(utc);
        }

        public static string ToString(DateTime date)
        {
            return string.Concat(DateTime.UtcNow.ToString(UtcDateFormat), UtcDateFooter);
        }
    }


    [DataContract]
    public class TicketModel
    {
        [DataMember]
        public int ID { get; set; }

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

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

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

        [DataMember]
        public bool IsUse { get; set; }

        [DataMember]
        public bool IsExit { get; set; }

        public TicketModel()
        {
            this.CreateDate = DateConvert.ToString(DateTime.Now);
        }

        public DateTime GetDateTime()
        {
            return DateConvert.ToDate(this.CreateDate);
        }
    }

}
コメントを投稿

Androider