diff Implab/Xml/SerializationHelpers.cs @ 264:3a6e18c432be v3

Added XmlToJson xsl transformation. Added JsonXmlReader.CreateJsonXmlReader(...) methods Added SerializationHelpers.SerializeJson/DeserializeJson methods
author cin
date Mon, 16 Apr 2018 18:43:49 +0300
parents 7c7e9ad6fe4a
children 6691aff01de1
line wrap: on
line diff
--- a/Implab/Xml/SerializationHelpers.cs	Mon Apr 16 02:12:57 2018 +0300
+++ b/Implab/Xml/SerializationHelpers.cs	Mon Apr 16 18:43:49 2018 +0300
@@ -2,10 +2,12 @@
 using System.Collections.Generic;
 using System.IO;
 using System.Linq;
+using System.Reflection;
 using System.Text;
 using System.Threading.Tasks;
 using System.Xml;
 using System.Xml.Linq;
+using System.Xml.Serialization;
 
 namespace Implab.Xml {
     public static class SerializationHelpers {
@@ -61,5 +63,34 @@
             using (var reader = node.CreateNavigator().ReadSubtree())
                 return SerializersPool<T>.Instance.Deserialize(reader);
         }
+
+        public static T DeserializeJson<T>(TextReader textReader) {
+            var options = new JsonXmlReaderOptions {
+                NamespaceUri = typeof(T).GetCustomAttribute<XmlRootAttribute>()?.Namespace,
+                RootName = typeof(T).Name,
+                FlattenArrays = true
+            };
+
+            using(var reader = JsonXmlReader.CreateJsonXmlReader(textReader, options))
+                return Deserialize<T>(reader);
+        }
+
+        public static T DeserializeJsonFromString<T>(string data) {
+            using(var reader = new StringReader(data)) {
+                return DeserializeJson<T>(reader);
+            }
+        }
+
+        public static void SerializeJson<T>(TextWriter writer, T obj) {
+            var doc = SerializeAsXmlDocument(obj);
+            XmlToJson.Default.Transform(doc, null, writer);
+        }
+
+        public static string SerializeJsonAsString<T>(T obj) {
+            using(var writer = new StringWriter()) {
+                SerializeJson(writer, obj);
+                return writer.ToString();
+            }
+        }
     }
 }