[Fork] Generic Json.NET startup project

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Xml;
using System.IO;
using System.Diagnostics;
using System.Collections.ObjectModel;
using System.Threading;
using System.ComponentModel;
using System.Xml.Linq;
using System.Reflection;
using System.Data;
using System.Xml.Schema;
using System.Text.RegularExpressions;
using System.Net;
using System.Xml.XPath;
using System.Globalization;
using System.ComponentModel.DataAnnotations;
using System.Collections;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;


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


    public static class JsonExtensions
    {
        const string JsonNamespace = @"http://james.newtonking.com/projects/json";
        const string ArrayAttributeName = @"Array";

        public static JToken ToJToken(this XElement xElement, bool omitRootObject, string deserializeRootElementName)
        {
            return xElement.ToJToken(omitRootObject, deserializeRootElementName, Enumerable.Empty<Func<XElement, IEnumerable<XElement>>>());
        }

        public static JToken ToJToken(this XElement xElement, bool omitRootObject, string deserializeRootElementName, IEnumerable<Func<XElement, IEnumerable<XElement>>> arrayQueries)
        {
            foreach (var query in arrayQueries)
            {
                var name = XName.Get(ArrayAttributeName, JsonNamespace);
                foreach (var element in query(xElement))
                {
                    element.SetAttributeValue(name, true);
                }
            }

            // Convert to Linq to XML JObject
            var settings = new JsonSerializerSettings { Converters = { new XmlNodeConverter { OmitRootObject = omitRootObject, DeserializeRootElementName = deserializeRootElementName } } };
            var root = JToken.FromObject(xElement, JsonSerializer.CreateDefault(settings));
            return root;
        }
    }

    public class Person
    {
        public string Name { get; set; }
        public string URL { get; set; }
        [XmlAttribute(AttributeName = "id")]
        [JsonProperty("@id")]
        public string Id { get; set; }
    }

    public class Root
    {
        [XmlElement]
        public List<Person> Person { get; set; }
    }

    // https://stackoverflow.com/questions/40978662/circular-reference-exception-when-serializing-an-object-containing-a-jtoken-to-x
    class TestClass
    {
        public static void Test()
        {
string xml = @"<?xml version='1.0' standalone='no'?>
<root>
  <perSon ID='1'>
    <name>Alan</name>
    <url>http://www.google.com</url>
  </perSon>
</root>";

            var xElement = XElement.Parse(xml);
            var jToken = xElement.ToJToken(true, "", 
                new Func<XElement, IEnumerable<XElement>> [] { e => e.Elements().Where(i => string.Equals(i.Name.LocalName, "Person", StringComparison.OrdinalIgnoreCase)) });

            var root = jToken.ToObject<Root>();

            Console.WriteLine("\nInput XML: ");
            Console.WriteLine(xml);

            Console.WriteLine("\nIntermediate JSON: ");
            Console.WriteLine(jToken);

            Console.WriteLine(string.Format("\nDeserialized {0} re-serialized to XML: ", root));
            Console.WriteLine(root.GetXml());
			
			Assert.IsTrue(root.Person.Count == 1);
        }
    }

	public class Program
	{
		public static void Main()
		{
			Console.WriteLine("Environment version: " + Environment.Version);
			Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);
			Console.WriteLine();

			try
			{
				TestClass.Test();
			}
			catch (Exception ex)
			{
				Console.WriteLine("Failed with unhandled exception: ");
				Console.WriteLine(ex);
				throw;
			}
		}
	}

    public class AssertionFailedException : System.Exception
    {
        public AssertionFailedException() : base() { }

        public AssertionFailedException(string s) : base(s) { }
    }

    public static class Assert
    {
        public static void IsTrue(bool value)
        {
            IsTrue(value, "failed");
        }

        public static void IsTrue(bool value, string message)
        {
            if (value == false)
                throw new AssertionFailedException(message ?? "failed");
        }
    }

    public static class XmlSerializationHelper
    {
        public static T LoadFromXml<T>(this string xmlString, XmlSerializer serial = null)
        {
            serial = serial ?? new XmlSerializer(typeof(T));
            T returnValue = default(T);
            using (StringReader reader = new StringReader(xmlString))
            {
                object result = serial.Deserialize(reader);
                if (result is T)
                {
                    returnValue = (T)result;
                }
            }
            return returnValue;
        }

        public static string GetXml<T>(this T obj, bool omitStandardNamespaces)
        {
			return obj.GetXml(null, omitStandardNamespaces);
        }
		
        public static string GetXml<T>(this T obj, XmlSerializer serializer = null, bool omitStandardNamespaces = false)
        {
            XmlSerializerNamespaces ns = null;
            if (omitStandardNamespaces)
            {
                ns = new XmlSerializerNamespaces();
                ns.Add("", ""); // Disable the xmlns:xsi and xmlns:xsd lines.
            }			
            using (var textWriter = new StringWriter())
            {
                var settings = new XmlWriterSettings() { Indent = true }; // For cosmetic purposes.
                using (var xmlWriter = XmlWriter.Create(textWriter, settings))
                    (serializer ?? new XmlSerializer(obj.GetType())).Serialize(xmlWriter, obj, ns);
                return textWriter.ToString();
            }
        }
    }
				
;