questions/43873024/newtonsoft-json-deserialize-xmlanyattribute

CSharp · Console

/Program.cs

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

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

    // https://stackoverflow.com/questions/43873024/newtonsoft-json-deserialize-xmlanyattribute


    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34283")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = true)]
    public partial class Scores : baseModel
    {
        private System.Xml.XmlAttribute[] anyAttrField;
        /// <remarks/>
        [System.Xml.Serialization.XmlAnyAttributeAttribute()]
        public System.Xml.XmlAttribute[] AnyAttr
        {
            get
            {
                return this.anyAttrField;
            }
            set
            {
                this.anyAttrField = value;
            }
        }
    }

    public partial class LandingPage : baseModel
    {
        private string projectNameField;
        private Scores scoresField;
        [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public string projectName
        {
            get { return this.projectNameField; }
            set { this.projectNameField = value; }
        }
        [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public Scores scores
        {
            get { return this.scoresField; }
            set { this.scoresField = value; }
        }
    }

    public partial class baseModel
    {
    }

    [JsonConverter(typeof(ScoresConverter))]
    public partial class Scores
    {
    }

    public class XmlAttributeArrayConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(XmlAttribute[]);
        } 

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
                return null;
            var dict = serializer.Deserialize<Dictionary<string, string>>(reader);
            var doc = new XmlDocument();
            return dict.Select(p => { var a = doc.CreateAttribute(p.Key); a.Value = p.Value; return a; }).ToArray();
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            // TODO: determine how to represent XmlAttribute values with non-empty NamespaceURI - or throw an exception.
            var attributes = (IEnumerable<XmlAttribute>)value;
            var dict = attributes.ToDictionary(a => a.Name, a => a.Value);
            serializer.Serialize(writer, dict);
        }
    }

    class ScoresConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(Scores);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
                return null;
            var attributes = (XmlAttribute[])new XmlAttributeArrayConverter().ReadJson(reader, typeof(XmlAttribute[]), null, serializer);
            return new Scores { AnyAttr = attributes };
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var scores = (Scores)value;
            if (scores.AnyAttr == null)
                writer.WriteNull();
            else
            {
                new XmlAttributeArrayConverter().WriteJson(writer, scores.AnyAttr, serializer);
            }
        }
    }

    class TestClass
    {
        public static void Test()
        {
            var json = GetJson();
            Console.WriteLine("Initial JSON: ");
            Console.WriteLine(json);
            var root = RoundTripJson<LandingPage>(json);
            RoundTripXml(root);
        }

        static void RoundTripXml<T>(T root)
        {
            var xml = root.GetXml();
            var root2 = xml.LoadFromXml<T>();
            var xml2 = root2.GetXml();

            Console.WriteLine("Round-tripped XML: ");
            Console.WriteLine(xml2);
            Assert.IsTrue(System.Xml.Linq.XNode.DeepEquals(System.Xml.Linq.XElement.Parse(xml), System.Xml.Linq.XElement.Parse(xml2)));
            Console.WriteLine("Serialized and re-serialized XML are identical. ");
        }

        static T RoundTripJson<T>(string json)
        {
            var root = JsonConvert.DeserializeObject<T>(json);
            var json2 = JsonConvert.SerializeObject(root, Newtonsoft.Json.Formatting.Indented);

			Console.WriteLine("Round-tripped JSON: ");
            Console.WriteLine(json2);
            return root;
        }

        static string GetJson()
        {
            var json = @"{
    ""projectName"":""PROJECTTEST"",
    ""scores"":{
        ""browLocker"":100,
        ""heavyAd"":0,
        ""walletRedirection"":0
    }
}";
            return json;
        }
    }

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

    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();
            }
        }
    }

    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);
        }
    }
;