Skip to content

Instantly share code, notes, and snippets.

@mattbrailsford
Created May 17, 2016 07:46
Show Gist options
  • Save mattbrailsford/8f45404766dc535d232978f30647f69e to your computer and use it in GitHub Desktop.
Save mattbrailsford/8f45404766dc535d232978f30647f69e to your computer and use it in GitHub Desktop.
public class Bootstrap : ApplicationEventHandler
{
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
ExamineManager.Instance.IndexProviderCollection["ExternalIndexer"].GatheringNodeData += (sender, args) =>
{
...
// Extract JSON properties
var fieldKeys = args.Fields.Keys.ToArray();
foreach (var key in fieldKeys)
{
var value = args.Fields[key];
if (value.DetectIsJson())
{
IndexNestedObject(args.Fields, JsonConvert.DeserializeObject(value), key);
}
}
...
}
}
private void IndexNestedObject(Dictionary<string, string> fields, object obj, string prefix)
{
var objType = obj.GetType();
if (objType == typeof(JObject))
{
var jObj = obj as JObject;
if (jObj != null)
{
foreach (var kvp in jObj)
{
var propKey = prefix + "_" + kvp.Key;
var valueType = kvp.Value.GetType();
if (typeof(JContainer).IsAssignableFrom(valueType))
{
IndexNestedObject(fields, kvp.Value, propKey);
}
else
{
fields.Add(propKey, kvp.Value.ToString().StripHtml());
}
}
}
}
else if (objType == typeof(JArray))
{
var jArr = obj as JArray;
if (jArr != null)
{
for (var i = 0; i < jArr.Count; i++)
{
var itm = jArr[i];
var propKey = prefix + "_" + i;
var valueType = itm.GetType();
if (typeof(JContainer).IsAssignableFrom(valueType))
{
IndexNestedObject(fields, itm, propKey);
}
else
{
fields.Add(propKey, itm.ToString().StripHtml());
}
}
}
}
}
}
public static class StringExtensions
{
public static bool DetectIsJson(this string input)
{
input = input.Trim();
if (input.StartsWith("{") && input.EndsWith("}"))
return true;
if (input.StartsWith("["))
return input.EndsWith("]");
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment