Skip to content

Commit 6d9d293

Browse files
committed
JsonExtensions: added methods to read array as hashset.
1 parent ab95c58 commit 6d9d293

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

TechnitiumLibrary/JsonExtensions.cs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,26 @@ private static string[] ReadArray(JsonElement jsonArray)
4848
}
4949
}
5050

51+
private static HashSet<string> ReadArrayAsSet(JsonElement jsonArray)
52+
{
53+
switch (jsonArray.ValueKind)
54+
{
55+
case JsonValueKind.Array:
56+
HashSet<string> set = new HashSet<string>(jsonArray.GetArrayLength());
57+
58+
foreach (JsonElement jsonItem in jsonArray.EnumerateArray())
59+
set.Add(jsonItem.GetString());
60+
61+
return set;
62+
63+
case JsonValueKind.Null:
64+
return null;
65+
66+
default:
67+
throw new InvalidOperationException();
68+
}
69+
}
70+
5171
private static T[] ReadArray<T>(JsonElement jsonArray, Func<string, T> getObject)
5272
{
5373
switch (jsonArray.ValueKind)
@@ -198,6 +218,23 @@ public static bool TryReadArray<T>(this JsonElement jsonElement, string property
198218
return false;
199219
}
200220

221+
public static HashSet<string> ReadArrayAsSet(this JsonElement jsonElement, string propertyName)
222+
{
223+
return ReadArrayAsSet(jsonElement.GetProperty(propertyName));
224+
}
225+
226+
public static bool TryReadArrayAsSet(this JsonElement jsonElement, string propertyName, out HashSet<string> set)
227+
{
228+
if (jsonElement.TryGetProperty(propertyName, out JsonElement jsonArray))
229+
{
230+
set = ReadArrayAsSet(jsonArray);
231+
return true;
232+
}
233+
234+
set = null;
235+
return false;
236+
}
237+
201238
public static Dictionary<TKey, TValue> ReadArrayAsMap<TKey, TValue>(this JsonElement jsonElement, string propertyName, Func<JsonElement, Tuple<TKey, TValue>> getObject)
202239
{
203240
return ReadArrayAsMap(jsonElement.GetProperty(propertyName), getObject);

0 commit comments

Comments
 (0)