Question35245256 JsonConstructor

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Collections;
using System.Runtime.Serialization;
using System.Data;
using System.ComponentModel;
using System.Dynamic;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Bson;

    public class Message
    {
        public string Text { get; private set; }
        public int Awesomeness { get; private set; }
        public Message(string Text, int Awesomeness)
        {
            if (Awesomeness < 1 || Awesomeness > 5)
            {
                throw new ArgumentOutOfRangeException("awesome");
            }
            this.Text = Text;
            this.Awesomeness = Awesomeness;
        }
    }

						
	public class Program
	{
		public static void Main()
		{
			Console.WriteLine(string.Format("Json.NET version: {0}.\n", typeof(JsonSerializer).Assembly.FullName));			

            var msg = new Message("This is some text", 2);
            var json = JsonConvert.SerializeObject(msg, Formatting.Indented);
            Console.WriteLine("");
            Console.WriteLine("Serialized Message:");
            Console.WriteLine(json);
            var msg2 = JsonConvert.DeserializeObject<Message>(json);
            if (msg.Awesomeness != msg2.Awesomeness || msg.Text != msg2.Text)
            {
                throw new InvalidOperationException("msg.Awesomeness != msg2.Awesomeness || msg.Text != msg2.Text");
            }

            var json2 = JsonConvert.SerializeObject(msg2);
            Console.WriteLine("");
            Console.WriteLine("Re-serialized Message:");
            Console.WriteLine(json);
		}
	}
;