Repository navigation
Expand file tree
/
Copy pathJsonPath.cs
More file actions
102 lines (86 loc) · 3.16 KB
/
Copy pathJsonPath.cs
File metadata and controls
102 lines (86 loc) · 3.16 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
using System.Linq;
using System.Reflection;
using System.Text.Json;
namespace JSONPredicate
{
internal static class JsonPath
{
public static object Evaluate(object obj, string path)
{
if (obj == null)
return null;
var properties = path.Split('.');
object current = obj;
foreach (var property in properties)
{
if (current == null)
return null;
// Check if it's an indexed access: array[0] or list[1]
if (property.Contains("[") && property.EndsWith("]"))
{
var parts = property.Split('[');
var propName = parts[0];
var indexStr = parts[1].TrimEnd(']');
// First get the property
var propInfo = current.GetType().GetProperty(propName,
BindingFlags.Public | BindingFlags.Instance);
if (propInfo == null)
return null;
var propValue = propInfo.GetValue(current);
// Then access array/list element if applicable
if (propValue is System.Collections.IList list)
{
if (int.TryParse(indexStr, out int index) && index >= 0 && index < list.Count)
{
current = list[index];
}
else
{
return null; // Invalid index
}
}
else
{
return null; // Not an indexable type
}
}
else
{
var propInfo = current.GetType().GetProperty(property,
BindingFlags.Public | BindingFlags.Instance);
if (propInfo == null)
return null;
current = propInfo.GetValue(current);
}
}
return current;
}
private static object DeserializeElement(JsonElement element)
{
object result = null;
switch (element.ValueKind)
{
case JsonValueKind.String:
result = DataTypes.TryParseDateTime(element.GetString()) ?? element.GetString();
break;
case JsonValueKind.Number:
result = element.TryGetInt32(out var i) ? i : element.GetDouble();
break;
case JsonValueKind.True:
result = true;
break;
case JsonValueKind.False:
result = false;
break;
case JsonValueKind.Array:
result = element.EnumerateArray().Select(DeserializeElement).ToArray();
break;
default:
result = null;
break;
}
;
return result;
}
}
}