<PackageReference Include="NJsonSchema" Version="1.2.5730.33570" />

JsonSchemaReferenceUtilities

public static class JsonSchemaReferenceUtilities
Provides utilities to resolve and set JSON schema references.
using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace NJsonSchema { public static class JsonSchemaReferenceUtilities { public static void UpdateAllTypeReferences(object root) { UpdateTypeReferences(root, root, new List<object>()); UpdateTypeReferencePaths(root, root, new List<object>()); } public static string ConvertJsonReferences(string data) { return data.Replace("$ref", "schemaReferencePath"); } public static string ConvertPropertyReferences(string data) { return data.Replace("schemaReferencePath", "$ref"); } private static void UpdateTypeReferencePaths(object root, object obj, List<object> checkedObjects) { if (obj != null && !(obj is string)) { JsonSchema4 jsonSchema = obj as JsonSchema4; if (jsonSchema != null && jsonSchema.SchemaReference != null) jsonSchema.SchemaReferencePath = JsonPathUtilities.GetJsonPath(root, jsonSchema.SchemaReference); if (obj is IDictionary) { foreach (object value2 in ((IDictionary)obj).Values) { UpdateTypeReferencePaths(root, value2, checkedObjects); } } else if (obj is IEnumerable) { foreach (object item in (IEnumerable)obj) { UpdateTypeReferencePaths(root, item, checkedObjects); } } else { foreach (PropertyInfo item2 in obj.GetType().GetRuntimeProperties().Where(delegate(PropertyInfo p) { if (p.CanRead) return p.GetCustomAttribute<JsonIgnoreAttribute>() == null; return false; })) { object value = item2.GetValue(obj); if (value != null && !checkedObjects.Contains(value)) { checkedObjects.Add(value); UpdateTypeReferencePaths(root, value, checkedObjects); } } } } } private static void UpdateTypeReferences(object root, object obj, List<object> checkedObjects) { if (obj != null && !(obj is string)) { JsonSchema4 jsonSchema = obj as JsonSchema4; if (jsonSchema != null && jsonSchema.SchemaReferencePath != null) jsonSchema.SchemaReference = JsonPathUtilities.GetObjectFromJsonPath(root, jsonSchema.SchemaReferencePath); if (obj is IDictionary) { foreach (object value2 in ((IDictionary)obj).Values) { UpdateTypeReferences(root, value2, checkedObjects); } } else if (obj is IEnumerable) { foreach (object item in (IEnumerable)obj) { UpdateTypeReferences(root, item, checkedObjects); } } else { foreach (PropertyInfo item2 in obj.GetType().GetRuntimeProperties().Where(delegate(PropertyInfo p) { if (p.CanRead) return p.GetCustomAttribute<JsonIgnoreAttribute>() == null; return false; })) { object value = item2.GetValue(obj); if (value != null && !checkedObjects.Contains(value)) { checkedObjects.Add(value); UpdateTypeReferences(root, value, checkedObjects); } } } } } } }