This repository was archived by the owner on Jun 22, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJsonHelper.cs
52 lines (48 loc) · 1.55 KB
/
JsonHelper.cs
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
49
50
51
52
using System.IO;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace GitMerger
{
public static class JsonHelper
{
private static readonly XmlDictionaryReaderQuotas InfiniteQuotas = new XmlDictionaryReaderQuotas
{
MaxArrayLength = int.MaxValue,
MaxBytesPerRead = int.MaxValue,
MaxDepth = int.MaxValue,
MaxNameTableCharCount = int.MaxValue,
MaxStringContentLength = int.MaxValue
};
public static void SerializeTo(XDocument content, Stream target)
{
using (var writer = JsonReaderWriterFactory.CreateJsonWriter(target))
content.Save(writer);
}
public static XDocument DeserializeFrom(string jsonString)
{
try
{
using (var reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(jsonString), InfiniteQuotas))
return XDocument.Load(reader);
}
catch
{
return null;
}
}
public static string SerializeObject<T>(T value)
{
var jsonFormatter = new JsonMediaTypeFormatter();
using (var ms = new MemoryStream())
{
jsonFormatter.WriteToStream(typeof(T), value, ms, Encoding.UTF8);
ms.Position = 0;
return Encoding.UTF8.GetString(ms.ToArray());
}
}
}
}