forked from TensorStack-AI/TensorStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPythonSerializer.cs
More file actions
84 lines (65 loc) · 2.58 KB
/
PythonSerializer.cs
File metadata and controls
84 lines (65 loc) · 2.58 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
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
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
using TensorStack.Common;
namespace TensorStack.Python
{
public static class PythonSerializer
{
private static JsonSerializerOptions _serializerOptions;
static PythonSerializer()
{
_serializerOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
NumberHandling = JsonNumberHandling.AllowReadingFromString,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
Converters = { new JsonStringEnumConverter() }
};
}
public static Dictionary<string, object> ToPythonDictionary<T>(this T source, params string[] ignoreProperties) where T : class
{
var json = JsonSerializer.Serialize<T>(source, _serializerOptions);
var dict = JsonSerializer.Deserialize<Dictionary<string, object>>(json, _serializerOptions);
return dict.ToJsonElementDictionary(ignoreProperties);
}
private static Dictionary<string, object> ToJsonElementDictionary(this Dictionary<string, object> source, params string[] ignoreProperties)
{
var result = new Dictionary<string, object>();
foreach (var (key, value) in source)
{
if (ignoreProperties.Contains(key))
continue;
result[key] = ConvertValue(value);
}
return result;
}
private static object ConvertValue(object value)
{
if (value is not JsonElement el)
return value;
return el.ValueKind switch
{
JsonValueKind.Number =>
el.TryGetInt64(out var l) ? l :
el.TryGetDouble(out var d) ? d :
null,
JsonValueKind.String =>
el.GetString(),
JsonValueKind.True => true,
JsonValueKind.False => false,
JsonValueKind.Array =>
el.EnumerateArray()
.Select(ConvertElement)
.ToArray(),
JsonValueKind.Object =>
el.EnumerateObject()
.ToDictionary(p => p.Name, p => ConvertElement(p.Value)),
JsonValueKind.Null => null,
_ => null
};
}
private static object ConvertElement(JsonElement el) => ConvertValue(el);
}
}