-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathXmlTextSerializer.cs
More file actions
48 lines (44 loc) · 1.37 KB
/
XmlTextSerializer.cs
File metadata and controls
48 lines (44 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
namespace Gilzoide.KeyValueStore.ObjectSerializers
{
public class XmlTextSerializer : ITextSerializer
{
private readonly static Dictionary<Type, XmlSerializer> _xmlSerializerCache = new();
public XmlSerializer GetCachedXmlSerializer(Type type)
{
if (!_xmlSerializerCache.TryGetValue(type, out XmlSerializer xmlSerializer))
{
xmlSerializer = new XmlSerializer(type);
_xmlSerializerCache[type] = xmlSerializer;
}
return xmlSerializer;
}
public bool TryDeserializeObject<T>(string text, out T value)
{
try
{
using (var reader = new StringReader(text))
{
value = (T) GetCachedXmlSerializer(typeof(T)).Deserialize(reader);
return true;
}
}
catch (Exception)
{
value = default;
return false;
}
}
public string SerializeObject<T>(T obj)
{
using (var writer = new StringWriter())
{
GetCachedXmlSerializer(typeof(T)).Serialize(writer, obj);
return writer.ToString();
}
}
}
}