2using Newtonsoft.Json.Linq;
7internal static class DefinitionDocumentJson
16 internal static List<T> Read<T>(
19 Func<T, string> identity,
20 Action<T>? legacy =
null,
21 StringComparer? identityComparer =
null) where T : class
25 var root = JToken.Parse(
28 { DuplicatePropertyNameHandling = DuplicatePropertyNameHandling.Error }) as JObject
29 ??
throw new InvalidDataException(
"Definition document must be a JSON object.");
31 var properties = root.Properties()
32 .Where(p =>
string.Equals(p.Name,
"Definitions", StringComparison.OrdinalIgnoreCase)).ToArray();
34 if (properties.Length == 0)
36 var singleton = read(root.ToString());
37 legacy?.Invoke(singleton);
41 if (properties.Length != 1 || root.Properties().Count() != 1)
42 throw new InvalidDataException(
43 "Definition document cannot combine Definitions with singleton properties.");
45 if (properties[0].Value is not JArray array)
46 throw new InvalidDataException(
"Definitions must be a non-null JSON array.");
48 var definitions =
new List<T>();
50 foreach (var token
in array)
52 if (token is not JObject member || member.Properties().Any(p =>
string.Equals(
55 StringComparison.OrdinalIgnoreCase)))
56 throw new InvalidDataException(
57 $
"Definitions[{definitions.Count}] must be a non-null definition object.");
59 definitions.Add(read(member.ToString()));
62 Check(definitions, identity, identityComparer: identityComparer);
65 catch (JsonException ex)
67 throw new InvalidDataException(
"Failed to deserialize definition document.", ex);
76 internal static void Check<T>(
77 IReadOnlyList<T>? definitions,
78 Func<T, string> identity,
79 bool allowUnnamedSingleton =
false,
80 StringComparer? identityComparer =
null) where T : class
82 if (definitions is
null)
83 throw new InvalidDataException(
"Definitions must not be null.");
85 var identities =
new HashSet<string>(identityComparer ?? StringComparer.Ordinal);
87 for (
int i = 0; i < definitions.Count; i++)
89 var member = definitions[i] ??
throw new InvalidDataException($
"Definitions[{i}] must not be null.");
90 var key = identity(member);
92 if (
string.IsNullOrWhiteSpace(key) && !(allowUnnamedSingleton && definitions.Count == 1))
93 throw new InvalidDataException($
"Definitions[{i}] requires a non-empty logical identity.");
95 if (!identities.Add(key))
96 throw new InvalidDataException($
"Duplicate definition identity '{key}'.");
106 internal static T Select<T>(
107 IReadOnlyList<T> definitions,
108 Func<T, string> identity,
110 StringComparer? identityComparer =
null)
114 if (definitions.Count != 1)
115 throw new InvalidDataException(
116 $
"Document contains {definitions.Count} definitions. Specify a logical identity or use LoadAll.");
118 return definitions[0];
121 ArgumentException.ThrowIfNullOrWhiteSpace(key);
123 foreach (var member
in definitions)
124 if ((identityComparer ?? StringComparer.Ordinal).Equals(identity(member), key))
127 throw new InvalidDataException($
"Definition '{key}' was not found in the document.");