-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathJson.cs
101 lines (93 loc) · 2.94 KB
/
Json.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
using System;
using System.IO;
using LanguageExt;
using LanguageExt.Common;
using static LanguageExt.Prelude;
using Newtonsoft.Json;
namespace LangExtEffSample
{
public interface JsonIO
{
T Deserialize<T>(Byte[] data);
T Deserialize<T>(string str);
string Serialize<T>(T obj);
}
public interface HasJson<RT>
where RT : struct
{
Eff<RT, JsonIO> EffJson { get; }
}
public static class JsonEff<RT>
where RT : struct, HasJson<RT>
{
public static Eff<RT, T> deserialize<T>(Byte[] json) =>
default(RT).EffJson.Map(j => j.Deserialize<T>(json));
public static Eff<RT, T> deserialize<T>(string json) =>
default(RT).EffJson.Map(j => j.Deserialize<T>(json));
public static Eff<RT, string> serialize<T>(T obj) =>
default(RT).EffJson.Map(j => j.Serialize<T>(obj));
}
public class LiveJsonIO : JsonIO
{
public string Serialize<T>(T obj) =>
JsonConvert.SerializeObject(obj);
public static string SerializeFormatted<T>(T obj) =>
JsonConvert.SerializeObject(obj, Formatting.Indented);
public T Deserialize<T>(Byte[] data)
{
// try
// {
using (var stream = new MemoryStream(data))
using (var reader = new StreamReader(stream, System.Text.Encoding.UTF8))
using (var jsonTextReader = new JsonTextReader(reader))
{
// try
// {
return JsonSerializer.Create().Deserialize<T>(jsonTextReader);
// }
// catch (Exception e)
// {
// return Fail<T>(Error.New(e));
// }
}
// }
// catch (Exception e)
// {
// return Left<Error, T>(Error.New(e));
// }
}
// public static Either<Error, T> Deserialize<T>(Stream stream)
// {
// try
// {
// using (var sr = new StreamReader(stream))
// using (var jsonTextReader = new JsonTextReader(sr))
// {
// try
// {
// return JsonSerializer.Create().Deserialize<T>(jsonTextReader);
// }
// catch (Exception e)
// {
// return Left<Error, T>(Error.New(e));
// }
// }
// }
// catch (Exception e)
// {
// return Left<Error, T>(Error.New(e));
// }
// }
public T Deserialize<T>(string str)
{
// try
// {
return JsonConvert.DeserializeObject<T>(str);
// }
// catch (Exception e)
// {
// return Left<Error, T>(Error.New(e));
// }
}
}
}