comparison 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
comparison
equal deleted inserted replaced
263:711572866e0c 264:3a6e18c432be
1 using System; 1 using System;
2 using System.Collections.Generic; 2 using System.Collections.Generic;
3 using System.IO; 3 using System.IO;
4 using System.Linq; 4 using System.Linq;
5 using System.Reflection;
5 using System.Text; 6 using System.Text;
6 using System.Threading.Tasks; 7 using System.Threading.Tasks;
7 using System.Xml; 8 using System.Xml;
8 using System.Xml.Linq; 9 using System.Xml.Linq;
10 using System.Xml.Serialization;
9 11
10 namespace Implab.Xml { 12 namespace Implab.Xml {
11 public static class SerializationHelpers { 13 public static class SerializationHelpers {
12 public static string SerializeAsString<T>(T obj) { 14 public static string SerializeAsString<T>(T obj) {
13 return SerializersPool<T>.Instance.SerializeAsString(obj); 15 return SerializersPool<T>.Instance.SerializeAsString(obj);
59 public static T DeserializeFromXmlNode<T>(XmlNode node) { 61 public static T DeserializeFromXmlNode<T>(XmlNode node) {
60 Safe.ArgumentNotNull(node, nameof(node)); 62 Safe.ArgumentNotNull(node, nameof(node));
61 using (var reader = node.CreateNavigator().ReadSubtree()) 63 using (var reader = node.CreateNavigator().ReadSubtree())
62 return SerializersPool<T>.Instance.Deserialize(reader); 64 return SerializersPool<T>.Instance.Deserialize(reader);
63 } 65 }
66
67 public static T DeserializeJson<T>(TextReader textReader) {
68 var options = new JsonXmlReaderOptions {
69 NamespaceUri = typeof(T).GetCustomAttribute<XmlRootAttribute>()?.Namespace,
70 RootName = typeof(T).Name,
71 FlattenArrays = true
72 };
73
74 using(var reader = JsonXmlReader.CreateJsonXmlReader(textReader, options))
75 return Deserialize<T>(reader);
76 }
77
78 public static T DeserializeJsonFromString<T>(string data) {
79 using(var reader = new StringReader(data)) {
80 return DeserializeJson<T>(reader);
81 }
82 }
83
84 public static void SerializeJson<T>(TextWriter writer, T obj) {
85 var doc = SerializeAsXmlDocument(obj);
86 XmlToJson.Default.Transform(doc, null, writer);
87 }
88
89 public static string SerializeJsonAsString<T>(T obj) {
90 using(var writer = new StringWriter()) {
91 SerializeJson(writer, obj);
92 return writer.ToString();
93 }
94 }
64 } 95 }
65 } 96 }