JsonPathUtilities
Utilities to work with JSON paths.
using NJsonSchema.Infrastructure;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace NJsonSchema
{
public static class JsonPathUtilities
{
internal const string ReferenceReplaceString = "__referencePath";
public static string GetJsonPath(object rootObject, object searchedObject)
{
return GetJsonPaths(rootObject, new List<object> {
searchedObject
})[searchedObject];
}
public static IReadOnlyDictionary<object, string> GetJsonPaths(object rootObject, IEnumerable<object> searchedObjects)
{
if (rootObject == null)
throw new ArgumentNullException("rootObject");
Dictionary<object, string> dictionary = searchedObjects.ToDictionary((Func<object, object>)((object o) => o), (Func<object, string>)((object o) => null));
FindJsonPaths(rootObject, dictionary, "#", new HashSet<object>());
if (dictionary.Any((KeyValuePair<object, string> p) => p.Value == null))
throw new InvalidOperationException("Could not find the JSON path of a referenced schema: Manually referenced schemas must be added to the 'Definitions' of a parent schema.");
return dictionary;
}
private static bool FindJsonPaths(object obj, Dictionary<object, string> searchedObjects, string basePath, HashSet<object> checkedObjects)
{
if (obj == null || obj is string || checkedObjects.Contains(obj))
return false;
if (searchedObjects.ContainsKey(obj)) {
searchedObjects[obj] = basePath;
if (searchedObjects.All((KeyValuePair<object, string> p) => p.Value != null))
return true;
}
checkedObjects.Add(obj);
if (obj is IDictionary) {
foreach (object key in ((IDictionary)obj).Keys) {
if (FindJsonPaths(((IDictionary)obj)[key], searchedObjects, basePath + "/" + key, checkedObjects))
return true;
}
} else if (obj is IEnumerable) {
int num = 0;
foreach (object item in (IEnumerable)obj) {
if (FindJsonPaths(item, searchedObjects, basePath + "/" + num, checkedObjects))
return true;
num++;
}
} else {
foreach (ReflectionCache.PropertyOrField item2 in from p in ReflectionCache.GetPropertiesAndFields(obj.GetType())
where p.CustomAttributes.JsonIgnoreAttribute == null
select p) {
object value = item2.GetValue(obj);
if (value != null) {
string name = item2.GetName();
if (obj is IJsonExtensionObject && name == "ExtensionData") {
if (FindJsonPaths(value, searchedObjects, basePath, checkedObjects))
return true;
} else if (FindJsonPaths(value, searchedObjects, basePath + "/" + name, checkedObjects)) {
return true;
}
}
}
}
return false;
}
}
}